Warning: file_get_contents(https://raw.githubusercontent.com/Den1xxx/Filemanager/master/languages/ru.json): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 88

Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 215

Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 216

Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 217

Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 218

Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 219

Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 220
PK!e>44CreateTagFromArrayTests.phpnu[ "foo:bar", ); $expected = ""; $this->assertEquals($expected, XML_Util::createTagFromArray($original)); } /** * @covers XML_Util::createTagFromArray() */ public function testCreateTagFromArrayWithQnameAndNamespace() { $original = array( "qname" => "foo:bar", "namespaceUri" => "http://foo.com", ); $expected = ""; $this->assertEquals($expected, XML_Util::createTagFromArray($original)); } /** * @covers XML_Util::createTagFromArray() */ public function testCreateTagFromArrayWithQnameAndNamespaceAndAttributes() { $original = array( "qname" => "foo:bar", "namespaceUri" => "http://foo.com", "attributes" => array( "key" => "value", "argh" => "fruit&vegetable" ), ); $expected = ""; $this->assertEquals($expected, XML_Util::createTagFromArray($original)); } /** * @covers XML_Util::createTagFromArray() */ public function testCreateTagFromArrayWithQnameAndNamespaceAndAttributesAndContent() { $original = array( "qname" => "foo:bar", "namespaceUri" => "http://foo.com", "attributes" => array( "key" => "value", "argh" => "fruit&vegetable" ), "content" => "I'm inside the tag", ); $expected = "I'm inside the tag"; $this->assertEquals($expected, XML_Util::createTagFromArray($original)); } /** * @covers XML_Util::createTagFromArray() */ public function testCreateTagFromArrayWithQnameAndAttributesAndContent() { $original = array( "qname" => "foo:bar", "attributes" => array( "key" => "value", "argh" => "fruit&vegetable" ), "content" => "I'm inside the tag", ); $expected = "I'm inside the tag"; $this->assertEquals($expected, XML_Util::createTagFromArray($original)); } /** * @covers XML_Util::createTagFromArray() */ public function testCreateTagFromArrayWithQnameAndNamespaceAndContent() { $original = array( "qname" => "foo:bar", "namespaceUri" => "http://foo.com", "content" => "I'm inside the tag", ); $expected = "I'm inside the tag"; $this->assertEquals($expected, XML_Util::createTagFromArray($original)); } /** * @covers XML_Util::createTagFromArray() */ public function testCreateTagFromArrayWithQnameAndNamespaceAndAttributesAndContentWithEntitiesNone() { $original = array( "qname" => "foo:bar", "namespaceUri" => "http://foo.com", "attributes" => array( "key" => "value", "argh" => "fruit&vegetable" ), "content" => "I'm inside the tag", ); $expected = "I'm inside the tag"; $this->assertEquals($expected, XML_Util::createTagFromArray($original, XML_UTIL_ENTITIES_NONE)); } /** * @covers XML_Util::createTagFromArray() */ public function testCreateTagFromArrayWithQnameAndNamespaceAndAttributesAndContentWithReplaceEntities() { $original = array( "qname" => "foo:bar", "namespaceUri" => "http://foo.com", "attributes" => array( "key" => "value", "argh" => "fruit&vegetable" ), "content" => "I'm inside the tag", ); $expected = "I'm inside the tag"; $this->assertEquals($expected, XML_Util::createTagFromArray($original, XML_UTIL_REPLACE_ENTITIES)); } /** * @covers XML_Util::createTagFromArray() */ public function testCreateTagFromArrayWithQnameAndNamespaceAndAttributesAndContentWithReplaceEntitiesAndMultilineFalse() { $original = array( "qname" => "foo:bar", "namespaceUri" => "http://foo.com", "attributes" => array( "key" => "value", "argh" => "fruit&vegetable" ), "content" => "I'm inside the tag", ); $multiline = false; $expected = "I'm inside the tag"; $this->assertEquals($expected, XML_Util::createTagFromArray($original, XML_UTIL_REPLACE_ENTITIES, $multiline)); } /** * @covers XML_Util::createTagFromArray() */ public function testCreateTagFromArrayWithQnameAndNamespaceAndAttributesAndContentWithReplaceEntitiesAndMultilineTrue() { $original = array( "qname" => "foo:bar", "namespaceUri" => "http://foo.com", "attributes" => array( "key" => "value", "argh" => "fruit&vegetable" ), "content" => "I'm inside the tag", ); $multiline = true; $expected = <<< EOF I'm inside the tag EOF; $this->assertEquals($expected, XML_Util::createTagFromArray($original, XML_UTIL_REPLACE_ENTITIES, $multiline)); } /** * @covers XML_Util::createTagFromArray() */ public function testCreateTagFromArrayWithQnameAndNamespaceAndAttributesAndContentWithReplaceEntitiesAndMultilineTrueAndIndent() { $original = array( "qname" => "foo:bar", "namespaceUri" => "http://foo.com", "attributes" => array( "key" => "value", "argh" => "fruit&vegetable" ), "content" => "I'm inside the tag", ); $multiline = true; $indent = " "; $expected = <<< EOF I'm inside the tag EOF; $this->assertEquals($expected, XML_Util::createTagFromArray($original, XML_UTIL_REPLACE_ENTITIES, $multiline, $indent)); } /** * @covers XML_Util::createTagFromArray() */ public function testCreateTagFromArrayWithQnameAndNamespaceAndAttributesAndContentWithReplaceEntitiesAndMultilineTrueAndIndentAndLinebreak() { $original = array( "qname" => "foo:bar", "namespaceUri" => "http://foo.com", "attributes" => array( "key" => "value", "argh" => "fruit&vegetable" ), "content" => "I'm inside the tag", ); $multiline = true; $indent = " "; $linebreak = "^"; $expected = "I'm inside the tag"; $this->assertEquals($expected, XML_Util::createTagFromArray($original, XML_UTIL_REPLACE_ENTITIES, $multiline, $indent, $linebreak)); } /** * @covers XML_Util::createTagFromArray() */ public function testCreateTagFromArrayWithQnameAndNamespaceAndAttributesAndContentWithReplaceEntitiesAndMultilineTrueAndIndentAndLinebreakAndSortAttributesTrue() { $original = array( "qname" => "foo:bar", "namespaceUri" => "http://foo.com", "attributes" => array( "key" => "value", "argh" => "fruit&vegetable" ), "content" => "I'm inside the tag", ); $multiline = true; $indent = " "; $linebreak = "^"; $sortAttributes = true; $expected = "I'm inside the tag"; $this->assertEquals($expected, XML_Util::createTagFromArray($original, XML_UTIL_REPLACE_ENTITIES, $multiline, $indent, $linebreak, $sortAttributes)); } /** * @covers XML_Util::createTagFromArray() */ public function testCreateTagFromArrayWithQnameAndNamespaceAndAttributesAndContentWithReplaceEntitiesAndMultilineTrueAndIndentAndLinebreakAndSortAttributesFalse() { $original = array( "qname" => "foo:bar", "namespaceUri" => "http://foo.com", "attributes" => array( "key" => "value", "argh" => "fruit&vegetable" ), "content" => "I'm inside the tag", ); $multiline = true; $indent = " "; $linebreak = "^"; $sortAttributes = false; $expected = "I'm inside the tag"; $this->assertEquals($expected, XML_Util::createTagFromArray($original, XML_UTIL_REPLACE_ENTITIES, $multiline, $indent, $linebreak, $sortAttributes)); } /** * @covers XML_Util::createTagFromArray() */ public function testCreateTagFromArrayWithInvalidArray() { $badArray = array( "foo" => "bar", ); $expectedError = "You must either supply a qualified name (qname) or local tag name (localPart)."; $this->assertEquals($expectedError, XML_Util::createTagFromArray($badArray)); } /** * @covers XML_Util::createTagFromArray() */ public function testCreateTagFromArrayWithNamespaceAndAttributesAndContentButWithoutQname() { $original = array( "namespaceUri" => "http://foo.com", "attributes" => array( "key" => "value", "argh" => "fruit&vegetable" ), "content" => "I'm inside the tag", ); $expectedError = "You must either supply a qualified name (qname) or local tag name (localPart)."; $this->assertEquals($expectedError, XML_Util::createTagFromArray($original)); } /** * @covers XML_Util::createTagFromArray() */ public function testCreateTagFromArrayWithNonScalarContent() { $badArray = array( 'content' => array('foo', 'bar'), ); $expectedError = "Supplied non-scalar value as tag content"; $this->assertEquals($expectedError, XML_Util::createTagFromArray($badArray)); } /** * @covers XML_Util::createTagFromArray() */ public function testCreateTagFromArrayWithArrayOfNamespaces() { $original = array( 'qname' => 'foo:bar', 'namespaces' => array('ns1' => 'uri1', 'ns2' => 'uri2'), ); $expected = ""; $this->assertEquals($expected, XML_Util::createTagFromArray($original)); } /** * @covers XML_Util::createTagFromArray() */ public function testCreateTagFromArrayWithQnameDerivedFromNamespaceUriAndLocalPart() { $original = array( 'namespaceUri' => 'http://bar.org', 'localPart' => 'foo' ); $expected = ""; $this->assertEquals($expected, XML_Util::createTagFromArray($original)); } /** * @covers XML_Util::createTagFromArray() */ public function testCreateTagFromArrayWithQnameDerivedFromNamespaceAndLocalPart() { $original = array( 'namespace' => 'http://foo.org', 'localPart' => 'bar' ); $expected = ""; $this->assertEquals($expected, XML_Util::createTagFromArray($original)); } /** * @covers XML_Util::createTagFromArray() */ public function testCreateTagFromArrayWithQnameDerivedFromLocalPart() { $original = array( 'namespace' => '', 'localPart' => 'bar' ); $expected = ""; $this->assertEquals($expected, XML_Util::createTagFromArray($original)); } /** * @covers XML_Util::createTagFromArray() */ public function testCreateTagFromArrayWithImplicitlyEmptyContentAndCollapseNoneDoesNotCollapseTag() { $original = array('qname' => 'tag1'); $expected = ""; $actual = XML_Util::createTagFromArray( $original, XML_UTIL_REPLACE_ENTITIES, // default $replaceEntities false, // default $multiline '_auto', // default $indent "\n", // default $linebreak true, // default $sortAttributes XML_UTIL_COLLAPSE_NONE ); $this->assertEquals($expected, $actual); } /** * @covers XML_Util::createTagFromArray() */ public function testCreateTagFromArrayForCdataWithExplicitlyEmptyContentDoesNotCollapseTag() { $original = array('qname' => 'tag1', 'content' => ''); $expected = ""; $this->assertEquals($expected, XML_Util::createTagFromArray($original, XML_UTIL_CDATA_SECTION)); } } PK!CReplaceEntitiesTests.phpnu[.'; } protected function getUtf8Data() { return 'This data contains special chars like <, >, & and " as well as ä, ö, ß, à and ê'; } /** * @covers XML_Util::replaceEntities() */ public function testReplaceEntitiesForSimpleData() { $expected = "This string contains < & >."; $this->assertEquals($expected, XML_Util::replaceEntities($this->getSimpleData())); } /** * @covers XML_Util::replaceEntities() */ public function testReplaceEntitiesForSimpleDataWithInvalidOptionReturnsOriginalData() { $expected = "This string contains < & >."; $this->assertEquals($expected, XML_Util::replaceEntities($this->getSimpleData(), 'INVALID_OPTION')); } /** * @covers XML_Util::replaceEntities() */ public function testReplaceEntitiesForSimpleDataWithEntitiesXml() { $expected = "This string contains < & >."; $this->assertEquals($expected, XML_Util::replaceEntities($this->getSimpleData(), XML_UTIL_ENTITIES_XML)); } /** * @covers XML_Util::replaceEntities() */ public function testReplaceEntitiesForSimpleDataWithEntitiesXmlAndEncoding() { $encoding = "UTF-8"; $expected = "This string contains < & >."; $this->assertEquals($expected, XML_Util::replaceEntities($this->getSimpleData(), XML_UTIL_ENTITIES_XML, $encoding)); } /** * @covers XML_Util::replaceEntities() */ public function testReplaceEntitiesForUtf8DataWithEntitiesXmlAndEncoding() { $encoding = "UTF-8"; $expected = "This data contains special chars like <, >, & and " as well as ä, ö, ß, à and ê"; $this->assertEquals($expected, XML_Util::replaceEntities($this->getUtf8Data(), XML_UTIL_ENTITIES_XML, $encoding)); } /** * @covers XML_Util::replaceEntities() */ public function testReplaceEntitiesForSimpleDataWithEntitiesXmlRequired() { $expected = "This string contains < & >."; $this->assertEquals($expected, XML_Util::replaceEntities($this->getSimpleData(), XML_UTIL_ENTITIES_XML_REQUIRED)); } /** * @covers XML_Util::replaceEntities() */ public function testReplaceEntitiesForSimpleDataWithEntitiesXmlRequiredAndEncoding() { $encoding = "UTF-8"; $expected = "This string contains < & >."; $this->assertEquals($expected, XML_Util::replaceEntities($this->getSimpleData(), XML_UTIL_ENTITIES_XML_REQUIRED, $encoding)); } /** * @covers XML_Util::replaceEntities() */ public function testReplaceEntitiesForUtf8DataWithEntitiesXmlRequiredAndEncoding() { $encoding = "UTF-8"; $expected = "This data contains special chars like <, >, & and " as well as ä, ö, ß, à and ê"; $this->assertEquals($expected, XML_Util::replaceEntities($this->getUtf8Data(), XML_UTIL_ENTITIES_XML_REQUIRED, $encoding)); } /** * @covers XML_Util::replaceEntities() */ public function testReplaceEntitiesForSimpleDataWithEntitiesHtml() { $expected = "This string contains < & >."; $this->assertEquals($expected, XML_Util::replaceEntities($this->getSimpleData(), XML_UTIL_ENTITIES_HTML)); } /** * @covers XML_Util::replaceEntities() */ public function testReplaceEntitiesForSimpleDataWithEntitiesHtmlAndEncoding() { $encoding = "UTF-8"; $expected = "This string contains < & >."; $this->assertEquals($expected, XML_Util::replaceEntities($this->getSimpleData(), XML_UTIL_ENTITIES_HTML, $encoding)); } /** * @covers XML_Util::replaceEntities() */ public function testReplaceEntitiesForUtf8DataWithEntitiesHtmlAndEncoding() { $encoding = "UTF-8"; $expected = "This data contains special chars like <, >, & and " as well as ä, ö, ß, à and ê"; $this->assertEquals($expected, XML_Util::replaceEntities($this->getUtf8Data(), XML_UTIL_ENTITIES_HTML, $encoding)); } } PK!یuApiVersionTests.phpnu[assertEquals('1.4', XML_Util::apiVersion()); } }PK!GsBug5392Tests.phpnu[, & and " as well as ä, ö, ß, à and ê'; $replacedResult = XML_Util::replaceEntities($original, XML_UTIL_ENTITIES_HTML, "UTF-8"); $reversedResult = XML_Util::reverseEntities($replacedResult, XML_UTIL_ENTITIES_HTML, "UTF-8"); $this->assertEquals($original, $reversedResult, "Failed bugcheck."); } } PK!4ejjCreateCDataSectionTests.phpnu["; $this->assertEquals($expected, XML_Util::createCDataSection($original)); } } PK!|\5CollapseEmptyTagsTests.phpnu["; $expected = ""; $this->assertEquals($expected, XML_Util::collapseEmptyTags($emptyTag)); } /** * @covers XML_Util::collapseEmptyTags() */ public function testCollapseEmptyTagsBasicUsageAlongsideNonemptyTag() { $emptyTag = ""; $otherTag = "baz"; $expected = "baz"; $this->assertEquals($expected, XML_Util::collapseEmptyTags($emptyTag . $otherTag)); } /** * @covers XML_Util::collapseEmptyTags() */ public function testCollapseEmptyTagsOnOneEmptyTagWithCollapseAll() { $emptyTag = ""; $expected = ""; $this->assertEquals($expected, XML_Util::collapseEmptyTags($emptyTag, XML_UTIL_COLLAPSE_ALL)); } /** * @covers XML_Util::collapseEmptyTags() */ public function testCollapseEmptyTagsOnOneEmptyTagAlongsideNonemptyTagWithCollapseAll() { $emptyTag = ""; $otherTag = "baz"; $expected = "baz"; $this->assertEquals($expected, XML_Util::collapseEmptyTags($emptyTag . $otherTag, XML_UTIL_COLLAPSE_ALL)); } /** * @covers XML_Util::collapseEmptyTags() */ public function testCollapseEmptyTagsOnOneEmptyTagAlongsideNonemptyTagAlongsideEmptyTagWithCollapseAll() { $emptyTag = ""; $otherTag = "baz"; $expected = "baz"; $this->assertEquals($expected, XML_Util::collapseEmptyTags($emptyTag . $otherTag . $emptyTag, XML_UTIL_COLLAPSE_ALL)); } /** * @covers XML_Util::collapseEmptyTags() */ public function testCollapseEmptyTagsOnOneEmptyPrefixedTagAlongsideNonemptyTagAlongsideEmptyPrefixedTagWithCollapseAll() { $emptyTag = ""; $otherTag = "baz"; $expected = "baz"; $this->assertEquals($expected, XML_Util::collapseEmptyTags($emptyTag . $otherTag . $emptyTag, XML_UTIL_COLLAPSE_ALL)); } /** * @covers XML_Util::collapseEmptyTags() */ public function testCollapseEmptyTagsOnOneEmptyNsPrefixedTagAlongsideNonemptyTagAlongsideEmptyNsPrefixedTagWithCollapseAll() { $emptyTag = ""; $otherTag = "baz"; $expected = "baz"; $this->assertEquals($expected, XML_Util::collapseEmptyTags($emptyTag . $otherTag . $emptyTag, XML_UTIL_COLLAPSE_ALL)); } /** * @covers XML_Util::collapseEmptyTags() */ public function testCollapseEmptyTagsOnOneEmptyTagWithCollapseXhtml() { $emptyTag = ""; $expected = ""; $this->assertEquals($expected, XML_Util::collapseEmptyTags($emptyTag, XML_UTIL_COLLAPSE_XHTML_ONLY)); } /** * @covers XML_Util::collapseEmptyTags() */ public function testCollapseEmptyTagsOnOneEmptyTagAlongsideNonemptyTagWithCollapseXhtml() { $emptyTag = ""; $otherTag = "baz"; $xhtmlTag = "

"; $expected = "
baz"; $this->assertEquals($expected, XML_Util::collapseEmptyTags($emptyTag . $xhtmlTag . $otherTag, XML_UTIL_COLLAPSE_XHTML_ONLY)); } /** * @covers XML_Util::collapseEmptyTags() */ public function testCollapseEmptyTagsOnOneEmptyTagWithCollapseNone() { $emptyTag = ""; $expected = ""; $this->assertEquals($expected, XML_Util::collapseEmptyTags($emptyTag, XML_UTIL_COLLAPSE_NONE)); } /** * @covers XML_Util::collapseEmptyTags() */ public function testCollapseEmptyTagsOnOneEmptyTagAlongsideNonemptyTagWithCollapseNone() { $emptyTag = ""; $otherTag = "baz"; $expected = "baz"; $this->assertEquals($expected, XML_Util::collapseEmptyTags($emptyTag . $otherTag, XML_UTIL_COLLAPSE_NONE)); } } PK!GGSplitQualifiedNameTests.phpnu[ 'xslt', 'localPart' => 'stylesheet', ); $this->assertEquals($expected, XML_Util::splitQualifiedName($original)); } /** * @covers XML_Util::splitQualifiedName() */ public function testSplitQualifiedNameWithNamespace() { $original = "stylesheet"; $namespace = "myNs"; $expected = array( 'namespace' => 'myNs', 'localPart' => 'stylesheet', ); $this->assertEquals($expected, XML_Util::splitQualifiedName($original, $namespace)); } } PK!YqBug21184Tests.phpnu[one'; $this->assertEquals($xml, XML_Util::collapseEmptyTags($xml, XML_UTIL_COLLAPSE_ALL)); } } PK!>MBug4950Tests.phpnu[ here!"; $namespaceUrl = null; $expected = " here!]]>"; $result = XML_Util::createTag($qname, $attributes, $content, $namespaceUrl, XML_UTIL_CDATA_SECTION); $this->assertEquals($expected, $result, "Failed bugcheck."); } } PK!YR""CreateStartElementTests.phpnu["; $this->assertEquals($expected, XML_Util::createStartElement($original)); } /** * @covers XML_Util::createStartElement() */ public function testCreateStartElementForTagWithAttributes() { $originalTag = "myNs:myTag"; $originalAttributes = array("foo" => "bar"); $expected = ""; $this->assertEquals($expected, XML_Util::createStartElement($originalTag, $originalAttributes)); } /** * @covers XML_Util::createStartElement() */ public function testCreateStartElementForTagWithEmptyAttributes() { $originalTag = "myNs:myTag"; $originalAttributes = ""; $expected = ""; $this->assertEquals($expected, XML_Util::createStartElement($originalTag, $originalAttributes)); } /** * @covers XML_Util::createStartElement() */ public function testCreateStartElementForTagWithAttributesAndNamespace() { $originalTag = "myNs:myTag"; $originalAttributes = array("foo" => "bar"); $originalNamespace = "http://www.w3c.org/myNs#"; $expected = ""; $this->assertEquals($expected, XML_Util::createStartElement($originalTag, $originalAttributes, $originalNamespace)); } /** * @covers XML_Util::createStartElement() */ public function testCreateStartElementForTagWithEmptyAttributesAndNonUriNamespace() { $originalTag = "myTag"; $originalAttributes = ""; $originalNamespace = "foo"; $expected = ""; $this->assertEquals($expected, XML_Util::createStartElement($originalTag, $originalAttributes, $originalNamespace)); } /** * @covers XML_Util::createStartElement() */ public function testCreateStartElementForTagWithAttributesAndNamespaceWithMultiline() { $originalTag = "myNs:myTag"; $originalAttributes = array("foo" => "bar"); $originalNamespace = "http://www.w3c.org/myNs#"; $expected = <<< EOF EOF; $multiline = true; $this->assertEquals($expected, XML_Util::createStartElement($originalTag, $originalAttributes, $originalNamespace, $multiline)); } /** * @covers XML_Util::createStartElement() */ public function testCreateStartElementForTagWithAttributesAndNamespaceWithMultilineAndIndent() { $originalTag = "myNs:myTag"; $originalAttributes = array("foo" => "bar"); $originalNamespace = "http://www.w3c.org/myNs#"; $expected = <<< EOF EOF; $multiline = true; $indent = " "; $this->assertEquals($expected, XML_Util::createStartElement($originalTag, $originalAttributes, $originalNamespace, $multiline, $indent)); } /** * @covers XML_Util::createStartElement() */ public function testCreateStartElementForTagWithAttributesAndNamespaceWithMultilineAndIndentAndLinebreak() { $originalTag = "myNs:myTag"; $originalAttributes = array("foo" => "bar"); $originalNamespace = "http://www.w3c.org/myNs#"; $expected = ""; $multiline = true; $indent = " "; $linebreak = "^"; $this->assertEquals($expected, XML_Util::createStartElement($originalTag, $originalAttributes, $originalNamespace, $multiline, $indent, $linebreak)); } /** * @covers XML_Util::createStartElement() */ public function testCreateStartElementForTagWithAttributesAndNamespaceWithMultilineAndIndentAndLinebreakAndSortAttributesIsTrue() { $originalTag = "myNs:myTag"; $originalAttributes = array("foo" => "bar", "boo" => "baz"); $originalNamespace = "http://www.w3c.org/myNs#"; $expected = ""; $multiline = true; $indent = " "; $linebreak = "^"; $sortAttributes = true; $this->assertEquals($expected, XML_Util::createStartElement($originalTag, $originalAttributes, $originalNamespace, $multiline, $indent, $linebreak, $sortAttributes)); } /** * @covers XML_Util::createStartElement() */ public function testCreateStartElementForTagWithAttributesAndNamespaceWithMultilineAndIndentAndLinebreakAndSortAttributesIsFalse() { $originalTag = "myNs:myTag"; $originalAttributes = array("foo" => "bar", "boo" => "baz"); $originalNamespace = "http://www.w3c.org/myNs#"; $expected = ""; $multiline = true; $indent = " "; $linebreak = "^"; $sortAttributes = false; $this->assertEquals($expected, XML_Util::createStartElement($originalTag, $originalAttributes, $originalNamespace, $multiline, $indent, $linebreak, $sortAttributes)); } } PK!ܬ$GetDocTypeDeclarationTests.phpnu["; $this->assertEquals($expected, XML_Util::getDocTypeDeclaration("rootTag")); } /** * @covers XML_Util::getDocTypeDeclaration() */ public function testGetDocTypeDeclarationUsingRootAndStringUri() { $expected = ""; $this->assertEquals($expected, XML_Util::getDocTypeDeclaration("rootTag", "myDocType.dtd")); } /** * @covers XML_Util::getDocTypeDeclaration() */ public function testGetDocTypeDeclarationUsingRootAndArrayUri() { $uri = array( 'uri' => 'http://pear.php.net/dtd/package-1.0', 'id' => '-//PHP//PEAR/DTD PACKAGE 0.1' ); $expected = ""; $this->assertEquals($expected, XML_Util::getDocTypeDeclaration("rootTag", $uri)); } /** * @covers XML_Util::getDocTypeDeclaration() */ public function testGetDocTypeDeclarationUsingRootAndArrayUriAndInternalDtd() { $uri = array( 'uri' => 'http://pear.php.net/dtd/package-1.0', 'id' => '-//PHP//PEAR/DTD PACKAGE 0.1' ); $dtdEntry = ''; $expected = <<< EOF ]> EOF; $this->assertEquals($expected, XML_Util::getDocTypeDeclaration("rootTag", $uri, $dtdEntry)); } } PK!GBug21177Tests.phpnu['; return array( array('', ''), array('', ''), array('', ''), array('', ''), ); } /** * @dataProvider getTestCandidate() */ public function testCollapseEmptyTagsForBug21177($original, $expected) { $this->assertEquals($expected, XML_Util::collapseEmptyTags($original, XML_UTIL_COLLAPSE_ALL), "Failed bugcheck."); } } PK!۩Bug18343Tests.phpnu[ "install", "attributes" => array( "as" => "Horde/Feed/fixtures/lexicon/http-p.moreover.com-cgi-local-page%2Fo=rss&s=Newsweek", "name" => "test/Horde/Feed/fixtures/lexicon/http-p.moreover.com-cgi-local-page%2Fo=rss&s=Newsweek", ) ); public function getFlagsToTest() { new XML_Util(); // for constants to be declared return array( array('no flag', null), array('false', false), array('ENTITIES_NONE', XML_UTIL_ENTITIES_NONE), array('ENTITIES_XML', XML_UTIL_ENTITIES_XML), array('ENTITIES_XML_REQUIRED', XML_UTIL_ENTITIES_XML_REQUIRED), array('ENTITIES_HTML', XML_UTIL_ENTITIES_HTML), array('REPLACE_ENTITIES', XML_UTIL_REPLACE_ENTITIES), ); } /** * @dataProvider getFlagsToTest() */ public function testCreateTagFromArrayForBug18343($key, $flag) { // all flags for the candidate input should return the same result $expected = <<< EOF EOF; $this->assertEquals($expected, XML_Util::createTagFromArray($this->tagArray, $flag), "Failed bugcheck for $key."); } } PK!ztReverseEntitiesTests.phpnu[."; $this->assertEquals($expected, XML_Util::reverseEntities($this->getSimpleData())); } /** * @covers XML_Util::reverseEntities() */ public function testReverseEntitiesForSimpleDataWithInvalidOptionReturnsOriginalData() { $expected = "This string contains < & >."; $this->assertEquals($expected, XML_Util::reverseEntities($this->getSimpleData(), 'INVALID_OPTION')); } /** * @covers XML_Util::reverseEntities() */ public function testReverseEntitiesForSimpleDataWithEntitiesXml() { $expected = "This string contains < & >."; $this->assertEquals($expected, XML_Util::reverseEntities($this->getSimpleData(), XML_UTIL_ENTITIES_XML)); } /** * @covers XML_Util::reverseEntities() */ public function testReverseEntitiesForSimpleDataWithEntitiesXmlAndEncoding() { $encoding = "UTF-8"; $expected = "This string contains < & >."; $this->assertEquals($expected, XML_Util::reverseEntities($this->getSimpleData(), XML_UTIL_ENTITIES_XML), $encoding); } /** * @covers XML_Util::reverseEntities() */ public function testReverseEntitiesForUtf8DataWithEntitiesXmlAndEncoding() { $encoding = "UTF-8"; $expected = "This data contains special chars like <, >, & and \" as well as ä, ö, ß, à and ê"; $this->assertEquals($expected, XML_Util::reverseEntities($this->getUtf8Data(), XML_UTIL_ENTITIES_XML), $encoding); } /** * @covers XML_Util::reverseEntities() */ public function testReverseEntitiesForSimpleDataWithEntitiesXmlRequired() { $expected = "This string contains < & >."; $this->assertEquals($expected, XML_Util::reverseEntities($this->getSimpleData(), XML_UTIL_ENTITIES_XML_REQUIRED)); } /** * @covers XML_Util::reverseEntities() */ public function testReverseEntitiesForSimpleDataWithEntitiesXmlRequiredAndEncoding() { $encoding = "UTF-8"; $expected = "This string contains < & >."; $this->assertEquals($expected, XML_Util::reverseEntities($this->getSimpleData(), XML_UTIL_ENTITIES_XML_REQUIRED, $encoding)); } /** * @covers XML_Util::reverseEntities() */ public function testReverseEntitiesForUtf8DataWithEntitiesXmlRequiredAndEncoding() { $encoding = "UTF-8"; $expected = "This data contains special chars like <, >, & and \" as well as ä, ö, ß, à and ê"; $this->assertEquals($expected, XML_Util::reverseEntities($this->getUtf8Data(), XML_UTIL_ENTITIES_XML_REQUIRED, $encoding)); } /** * @covers XML_Util::reverseEntities() */ public function testReverseEntitiesForSimpleDataWithEntitiesHtml() { $expected = "This string contains < & >."; $this->assertEquals($expected, XML_Util::reverseEntities($this->getSimpleData(), XML_UTIL_ENTITIES_HTML)); } /** * @covers XML_Util::reverseEntities() */ public function testReverseEntitiesForSimpleDataWithEntitiesHtmlAndEncoding() { $encoding = "UTF-8"; $expected = "This string contains < & >."; $this->assertEquals($expected, XML_Util::reverseEntities($this->getSimpleData(), XML_UTIL_ENTITIES_HTML, $encoding)); } /** * @covers XML_Util::reverseEntities() */ public function testReverseEntitiesForUtf8DataWithEntitiesHtmlAndEncoding() { $encoding = "UTF-8"; $expected = "This data contains special chars like <, >, & and \" as well as ä, ö, ß, à and ê"; $this->assertEquals($expected, XML_Util::reverseEntities($this->getUtf8Data(), XML_UTIL_ENTITIES_HTML, $encoding)); } } PK!~$[eeCreateEndElementTests.phpnu["; $this->assertEquals($expected, XML_Util::createEndElement($original)); } /** * @covers XML_Util::createEndElement() */ public function testCreateEndElementWithNamespacedTag() { $original = "myNs:myTag"; $expected = ""; $this->assertEquals($expected, XML_Util::createEndElement($original)); } } PK!!AbstractUnitTests.phpnu[ "bar"); $expected = ""; $this->assertEquals($expected, XML_Util::createTag($originalTag, $originalAttributes)); } /** * @covers XML_Util::createTag() */ public function testCreateTagForTagWithAttributesAndContent() { $originalTag = "myNs:myTag"; $originalAttributes = array("foo" => "bar"); $originalContent = "This is inside the tag"; $expected = "This is inside the tag"; $this->assertEquals($expected, XML_Util::createTag($originalTag, $originalAttributes, $originalContent)); } /** * @covers XML_Util::createTag() */ public function testCreateTagForTagWithAttributesAndContentAndNamespace() { $originalTag = "myNs:myTag"; $originalAttributes = array("foo" => "bar"); $originalContent = "This is inside the tag"; $originalNamespace = "http://www.w3c.org/myNs#"; $expected = "This is inside the tag"; $this->assertEquals($expected, XML_Util::createTag($originalTag, $originalAttributes, $originalContent, $originalNamespace)); } /** * @covers XML_Util::createTag() */ public function testCreateTagForTagWithAttributesAndContentAndNamespaceWithCDataSection() { $originalTag = "myNs:myTag"; $originalAttributes = array("foo" => "bar"); $originalContent = "This is inside the tag and has < & @ > in it"; $originalNamespace = "http://www.w3c.org/myNs#"; $expected = " in it]]>"; $this->assertEquals($expected, XML_Util::createTag($originalTag, $originalAttributes, $originalContent, $originalNamespace, XML_UTIL_CDATA_SECTION)); } /** * @covers XML_Util::createTag() */ public function testCreateTagForTagWithAttributesAndContentAndNamespaceWithReplaceEntities() { $originalTag = "myNs:myTag"; $originalAttributes = array("foo" => "bar"); $originalContent = "This is inside the tag and has < & @ > in it"; $originalNamespace = "http://www.w3c.org/myNs#"; $expected = "This is inside the tag and has < & @ > in it"; $this->assertEquals($expected, XML_Util::createTag($originalTag, $originalAttributes, $originalContent, $originalNamespace, XML_UTIL_REPLACE_ENTITIES)); } /** * @covers XML_Util::createTag() */ public function testCreateTagForTagWithAttributesAndContentAndNamespaceWithReplaceEntitiesAndMultilineFalse() { $originalTag = "myNs:myTag"; $originalAttributes = array("foo" => "bar"); $originalContent = "This is inside the tag and has < & @ > in it"; $originalNamespace = "http://www.w3c.org/myNs#"; $multiline = false; $expected = "This is inside the tag and has < & @ > in it"; $this->assertEquals($expected, XML_Util::createTag($originalTag, $originalAttributes, $originalContent, $originalNamespace, XML_UTIL_REPLACE_ENTITIES, $multiline)); } /** * @covers XML_Util::createTag() */ public function testCreateTagForTagWithAttributesAndContentAndNamespaceWithReplaceEntitiesAndMultilineTrue() { $originalTag = "myNs:myTag"; $originalAttributes = array("foo" => "bar"); $originalContent = "This is inside the tag and has < & @ > in it"; $originalNamespace = "http://www.w3c.org/myNs#"; $multiline = true; $expected = <<< EOF This is inside the tag and has < & @ > in it EOF; $this->assertEquals($expected, XML_Util::createTag($originalTag, $originalAttributes, $originalContent, $originalNamespace, XML_UTIL_REPLACE_ENTITIES, $multiline)); } /** * @covers XML_Util::createTag() */ public function testCreateTagForTagWithAttributesAndContentAndNamespaceWithReplaceEntitiesAndMultilineTrueAndIndent() { $originalTag = "myNs:myTag"; $originalAttributes = array("foo" => "bar"); $originalContent = "This is inside the tag and has < & @ > in it"; $originalNamespace = "http://www.w3c.org/myNs#"; $multiline = true; $indent = " "; $expected = <<< EOF This is inside the tag and has < & @ > in it EOF; $this->assertEquals($expected, XML_Util::createTag($originalTag, $originalAttributes, $originalContent, $originalNamespace, XML_UTIL_REPLACE_ENTITIES, $multiline, $indent)); } /** * @covers XML_Util::createTag() */ public function testCreateTagForTagWithAttributesAndContentAndNamespaceWithReplaceEntitiesAndMultilineTrueAndIndentAndLinebreak() { $originalTag = "myNs:myTag"; $originalAttributes = array("foo" => "bar"); $originalContent = "This is inside the tag and has < & @ > in it"; $originalNamespace = "http://www.w3c.org/myNs#"; $multiline = true; $indent = " "; $linebreak = "^"; $expected = "This is inside the tag and has < & @ > in it"; $this->assertEquals($expected, XML_Util::createTag($originalTag, $originalAttributes, $originalContent, $originalNamespace, XML_UTIL_REPLACE_ENTITIES, $multiline, $indent, $linebreak)); } /** * @covers XML_Util::createTag() */ public function testCreateTagForTagWithAttributesAndContentAndNamespaceWithReplaceEntitiesAndMultilineTrueAndIndentAndLinebreakAndSortAttributesTrue() { $originalTag = "myNs:myTag"; $originalAttributes = array("foo" => "bar", "boo" => "baz"); $originalContent = "This is inside the tag and has < & @ > in it"; $originalNamespace = "http://www.w3c.org/myNs#"; $multiline = true; $indent = " "; $linebreak = "^"; $sortAttributes = true; $expected = "This is inside the tag and has < & @ > in it"; $this->assertEquals($expected, XML_Util::createTag($originalTag, $originalAttributes, $originalContent, $originalNamespace, XML_UTIL_REPLACE_ENTITIES, $multiline, $indent, $linebreak, $sortAttributes)); } /** * @covers XML_Util::createTag() */ public function testCreateTagForTagWithAttributesAndContentAndNamespaceWithReplaceEntitiesAndMultilineTrueAndIndentAndLinebreakAndSortAttributesFalse() { $originalTag = "myNs:myTag"; $originalAttributes = array("foo" => "bar", "boo" => "baz"); $originalContent = "This is inside the tag and has < & @ > in it"; $originalNamespace = "http://www.w3c.org/myNs#"; $multiline = true; $indent = " "; $linebreak = "^"; $sortAttributes = false; $expected = "This is inside the tag and has < & @ > in it"; $this->assertEquals($expected, XML_Util::createTag($originalTag, $originalAttributes, $originalContent, $originalNamespace, XML_UTIL_REPLACE_ENTITIES, $multiline, $indent, $linebreak, $sortAttributes)); } } PK!Df:GetXmlDeclarationTests.phpnu["; $this->assertEquals($expected, XML_Util::getXMLDeclaration($version)); } /** * @covers XML_Util::getXMLDeclaration() */ public function testGetXMLDeclarationUsingVersionAndEncodingAndStandalone() { $version = "1.0"; $encoding = "UTF-8"; $standalone = true; $expected = ""; $this->assertEquals($expected, XML_Util::getXMLDeclaration($version, $encoding, $standalone)); } /** * @covers XML_Util::getXMLDeclaration() */ public function testGetXMLDeclarationUsingVersionAndStandalone() { $version = "1.0"; $encoding = null; $standalone = true; $expected = ""; $this->assertEquals($expected, XML_Util::getXMLDeclaration($version, $encoding, $standalone)); } } PK!ZtAttributesToStringTests.phpnu[ 'bar','boo' => 'baz',); $expected = " boo=\"baz\" foo=\"bar\""; $this->assertEquals($expected, XML_Util::attributesToString($original)); } /** * @covers XML_Util::attributesToString() */ public function testAttributesToStringWithExplicitSortTrue() { $original = array('foo' => 'bar','boo' => 'baz',); $expected = " boo=\"baz\" foo=\"bar\""; $sort = true; $this->assertEquals($expected, XML_Util::attributesToString($original, $sort)); } /** * @covers XML_Util::attributesToString() */ public function testAttributesToStringWithExplicitSortFalse() { $original = array('foo' => 'bar','boo' => 'baz',); $expected = " foo=\"bar\" boo=\"baz\""; $sort = false; $this->assertEquals($expected, XML_Util::attributesToString($original, $sort)); } /** * @covers XML_Util::attributesToString() */ public function testAttributesToStringWithMultilineFalse() { $original = array('foo' => 'bar','boo' => 'baz',); $expected = " boo=\"baz\" foo=\"bar\""; $sort = true; $multiline = false; $this->assertEquals($expected, XML_Util::attributesToString($original, $sort, $multiline)); } /** * @covers XML_Util::attributesToString() */ public function testAttributesToStringWithMultilineTrue() { $original = array('foo' => 'bar','boo' => 'baz',); $expected = <<< EOF boo="baz" foo="bar" EOF; $sort = true; $multiline = true; $this->assertEquals($expected, XML_Util::attributesToString($original, $sort, $multiline)); } /** * @covers XML_Util::attributesToString() */ public function testAttributesToStringWithExplicitIndent() { $original = array('foo' => 'bar','boo' => 'baz',); $expected = " boo=\"baz\"\n foo=\"bar\""; $sort = true; $multiline = true; $indent = ' '; // 8 spaces $this->assertEquals($expected, XML_Util::attributesToString($original, $sort, $multiline, $indent)); } /** * @covers XML_Util::attributesToString() */ public function testAttributesToStringWithExplicitLinebreak() { $original = array('foo' => 'bar','boo' => 'baz',); $expected = " boo=\"baz\"\n^foo=\"bar\""; $sort = true; $multiline = true; $linebreak = '^'; // some dummy character $this->assertEquals($expected, XML_Util::attributesToString($original, $sort, $multiline, $linebreak)); } /** * @covers XML_Util::attributesToString() */ public function testAttributesToStringWithOptionsThatIncludesSort() { $original = array('foo' => 'bar','boo' => 'baz',); $options = array( 'multiline' => true, 'indent' => '----', 'linebreak' => "^", 'entities' => XML_UTIL_ENTITIES_XML, 'sort' => true, ); $expected = " boo=\"baz\"\n----foo=\"bar\""; $this->assertEquals($expected, XML_Util::attributesToString($original, $options)); } /** * @covers XML_Util::attributesToString() */ public function testAttributesToStringWithOptionsThatExcludesSort() { $original = array('foo' => 'bar','boo' => 'baz',); $options = array( 'multiline' => true, 'indent' => '----', 'linebreak' => "^", 'entities' => XML_UTIL_ENTITIES_XML, ); $expected = " boo=\"baz\"\n----foo=\"bar\""; $this->assertEquals($expected, XML_Util::attributesToString($original, $options)); } /** * @covers XML_Util::attributesToString() */ public function testAttributesToStringWithEntitiesNone() { $original = array("foo" => "b@&r", "boo" => "b>assertEquals($expected, XML_Util::attributesToString($original, $sort, $multiline, $linebreak, PHP_EOL, XML_UTIL_ENTITIES_NONE)); } /** * @covers XML_Util::attributesToString() */ public function testAttributesToStringWithEntitiesXml() { $original = array("foo" => "b@&r", "boo" => "b>assertEquals($expected, XML_Util::attributesToString($original, $sort, $multiline, $linebreak, PHP_EOL, XML_UTIL_ENTITIES_XML)); } /** * @covers XML_Util::attributesToString() */ public function testAttributesToStringWithEntitiesXmlRequired() { $original = array("foo" => "b@&r", "boo" => "b><z\" foo=\"b@&r\""; $sort = true; $multiline = false; $linebreak = ' '; $this->assertEquals($expected, XML_Util::attributesToString($original, $sort, $multiline, $linebreak, PHP_EOL, XML_UTIL_ENTITIES_XML_REQUIRED)); } /** * @covers XML_Util::attributesToString() */ public function testAttributesToStringWithEntitiesHtml() { $original = array("foo" => "b@&r", "boo" => "b>assertEquals($expected, XML_Util::attributesToString($original, $sort, $multiline, $linebreak, PHP_EOL, XML_UTIL_ENTITIES_HTML)); } /** * Tag attributes should not be treated as CDATA, * so the operation will instead quietly use XML_UTIL_ENTITIES_XML. * * @covers XML_Util::attributesToString() */ public function testAttributesToStringWithCDataSectionForSingleAttribute() { $original = array('foo' => 'bar'); // need exactly one attribute here $options = array( 'sort' => true, // doesn't matter for this testcase 'multiline' => false, // doesn't matter for this testcase 'indent' => null, // doesn't matter for this testcase 'linebreak' => null, // doesn't matter for this testcase 'entities' => XML_UTIL_CDATA_SECTION, // DOES matter for this testcase ); $expected = " foo=\"bar\""; $this->assertEquals($expected, XML_Util::attributesToString($original, $options)); } /** * Tag attributes should not be treated as CDATA, * so the operation will instead quietly use XML_UTIL_ENTITIES_XML. * * @covers XML_Util::attributesToString() */ public function testAttributesToStringWithCDataSectionForMultipleAttributesAndMultilineFalse() { $original = array('foo' => 'bar', 'boo' => 'baz'); // need more than one attribute here $options = array( 'sort' => true, // doesn't matter for this testcase 'multiline' => false, // DOES matter for this testcase, must be false 'indent' => null, // doesn't matter for this testcase 'linebreak' => null, // doesn't matter for this testcase 'entities' => XML_UTIL_CDATA_SECTION, // DOES matter for this testcase ); $expected = " boo=\"baz\" foo=\"bar\""; $this->assertEquals($expected, XML_Util::attributesToString($original, $options)); } } PK!ݑhIsValidNameTests.phpnu[assertTrue($result); } /** * @covers XML_Util::isValidName() */ public function testIsValidNameForTagNameWithInvalidCharacter() { $tagName = "invalidTag?"; $result = XML_Util::isValidName($tagName); $this->assertInstanceOf('PEAR_Error', $result); $expectedError = "XML names may only contain alphanumeric chars, period, hyphen, colon and underscores"; $this->assertEquals($expectedError, $result->getMessage()); } /** * @covers XML_Util::isValidName() */ public function testIsValidNameForTagNameWithInvalidStartingCharacter() { $tagName = "1234five"; $result = XML_Util::isValidName($tagName); $this->assertInstanceOf('PEAR_Error', $result); $expectedError = "XML names may only start with letter or underscore"; $this->assertEquals($expectedError, $result->getMessage()); } /** * @covers XML_Util::isValidName() */ public function testIsValidNameForInt() { $tagName = 1; $result = XML_Util::isValidName($tagName); $this->assertInstanceOf('PEAR_Error', $result); $expectedError = "XML names may only start with letter or underscore"; $this->assertEquals($expectedError, $result->getMessage()); } /** * @covers XML_Util::isValidName() */ public function testIsValidNameForEmptyString() { $tagName = ''; $result = XML_Util::isValidName($tagName); $this->assertInstanceOf('PEAR_Error', $result); $expectedError = "XML names may only start with letter or underscore"; $this->assertEquals($expectedError, $result->getMessage()); } } PK!TTCreateCommentTests.phpnu["; $this->assertEquals($expected, XML_Util::createComment($original)); } } PK!rvRaiseErrorTests.phpnu[assertInstanceOf('PEAR_Error', $error); $this->assertEquals($message, $error->getMessage()); $this->assertEquals($code, $error->getCode()); } } PK!`f3##.pear/Structures_Graph/tests/BasicGraphTest.phpnu[ | // +-----------------------------------------------------------------------------+ // require_once dirname(__FILE__) . '/helper.inc'; /** * @access private */ class BasicGraph extends \PHPUnit\Framework\TestCase { var $_graph = null; function test_create_graph() { $this->_graph = new Structures_Graph(); $this->assertTrue(is_a($this->_graph, 'Structures_Graph')); } function test_add_node() { $this->_graph = new Structures_Graph(); $data = 1; $node = new Structures_Graph_Node($data); $this->_graph->addNode($node); $node = new Structures_Graph_Node($data); $this->_graph->addNode($node); $node = new Structures_Graph_Node($data); $this->_graph->addNode($node); $this->assertTrue(true); } function test_connect_node() { $this->_graph = new Structures_Graph(); $data = 1; $node1 = new Structures_Graph_Node($data); $node2 = new Structures_Graph_Node($data); $this->_graph->addNode($node1); $this->_graph->addNode($node2); $node1->connectTo($node2); $node =& $this->_graph->getNodes(); $node =& $node[0]; $node = $node->getNeighbours(); $node =& $node[0]; /* ZE1 == and === operators fail on $node,$node2 because of the recursion introduced by the _graph field in the Node object. So, we'll use the stupid method for reference testing */ $node = true; $this->assertTrue($node2); $node = false; $this->assertFalse($node2); } function test_data_references() { $this->_graph = new Structures_Graph(); $data = 1; $node = new Structures_Graph_Node(); $node->setData($data); $this->_graph->addNode($node); $data = 2; $dataInNode =& $this->_graph->getNodes(); $dataInNode =& $dataInNode[0]; $dataInNode =& $dataInNode->getData(); $this->assertEquals($data, $dataInNode); } function test_metadata_references() { $this->_graph = new Structures_Graph(); $data = 1; $node = new Structures_Graph_Node(); $node->setMetadata('5', $data); $data = 2; $dataInNode =& $node->getMetadata('5'); $this->assertEquals($data, $dataInNode); } function test_metadata_key_exists() { $this->_graph = new Structures_Graph(); $data = 1; $node = new Structures_Graph_Node(); $node->setMetadata('5', $data); $this->assertTrue($node->metadataKeyExists('5')); $this->assertFalse($node->metadataKeyExists('1')); } function test_directed_degree() { $this->_graph = new Structures_Graph(true); $node = array(); $node[] = new Structures_Graph_Node(); $node[] = new Structures_Graph_Node(); $node[] = new Structures_Graph_Node(); $this->_graph->addNode($node[0]); $this->_graph->addNode($node[1]); $this->_graph->addNode($node[2]); $this->assertEquals(0, $node[0]->inDegree(), 'inDegree test failed for node 0 with 0 arcs'); $this->assertEquals(0, $node[1]->inDegree(), 'inDegree test failed for node 1 with 0 arcs'); $this->assertEquals(0, $node[2]->inDegree(), 'inDegree test failed for node 2 with 0 arcs'); $this->assertEquals(0, $node[0]->outDegree(), 'outDegree test failed for node 0 with 0 arcs'); $this->assertEquals(0, $node[1]->outDegree(), 'outDegree test failed for node 1 with 0 arcs'); $this->assertEquals(0, $node[2]->outDegree(), 'outDegree test failed for node 2 with 0 arcs'); $node[0]->connectTo($node[1]); $this->assertEquals(0, $node[0]->inDegree(), 'inDegree test failed for node 0 with 1 arc'); $this->assertEquals(1, $node[1]->inDegree(), 'inDegree test failed for node 1 with 1 arc'); $this->assertEquals(0, $node[2]->inDegree(), 'inDegree test failed for node 2 with 1 arc'); $this->assertEquals(1, $node[0]->outDegree(), 'outDegree test failed for node 0 with 1 arc'); $this->assertEquals(0, $node[1]->outDegree(), 'outDegree test failed for node 1 with 1 arc'); $this->assertEquals(0, $node[2]->outDegree(), 'outDegree test failed for node 2 with 1 arc'); $node[0]->connectTo($node[2]); $this->assertEquals(0, $node[0]->inDegree(), 'inDegree test failed for node 0 with 2 arcs'); $this->assertEquals(1, $node[1]->inDegree(), 'inDegree test failed for node 1 with 2 arcs'); $this->assertEquals(1, $node[2]->inDegree(), 'inDegree test failed for node 2 with 2 arcs'); $this->assertEquals(2, $node[0]->outDegree(), 'outDegree test failed for node 0 with 2 arcs'); $this->assertEquals(0, $node[1]->outDegree(), 'outDegree test failed for node 1 with 2 arcs'); $this->assertEquals(0, $node[2]->outDegree(), 'outDegree test failed for node 2 with 2 arcs'); } function test_undirected_degree() { $this->_graph = new Structures_Graph(false); $node = array(); $node[] = new Structures_Graph_Node(); $node[] = new Structures_Graph_Node(); $node[] = new Structures_Graph_Node(); $this->_graph->addNode($node[0]); $this->_graph->addNode($node[1]); $this->_graph->addNode($node[2]); $this->assertEquals(0, $node[0]->inDegree(), 'inDegree test failed for node 0 with 0 arcs'); $this->assertEquals(0, $node[1]->inDegree(), 'inDegree test failed for node 1 with 0 arcs'); $this->assertEquals(0, $node[2]->inDegree(), 'inDegree test failed for node 2 with 0 arcs'); $this->assertEquals(0, $node[0]->outDegree(), 'outDegree test failed for node 0 with 0 arcs'); $this->assertEquals(0, $node[1]->outDegree(), 'outDegree test failed for node 1 with 0 arcs'); $this->assertEquals(0, $node[2]->outDegree(), 'outDegree test failed for node 2 with 0 arcs'); $node[0]->connectTo($node[1]); $this->assertEquals(1, $node[0]->inDegree(), 'inDegree test failed for node 0 with 1 arc'); $this->assertEquals(1, $node[1]->inDegree(), 'inDegree test failed for node 1 with 1 arc'); $this->assertEquals(0, $node[2]->inDegree(), 'inDegree test failed for node 2 with 1 arc'); $this->assertEquals(1, $node[0]->outDegree(), 'outDegree test failed for node 0 with 1 arc'); $this->assertEquals(1, $node[1]->outDegree(), 'outDegree test failed for node 1 with 1 arc'); $this->assertEquals(0, $node[2]->outDegree(), 'outDegree test failed for node 2 with 1 arc'); $node[0]->connectTo($node[2]); $this->assertEquals(2, $node[0]->inDegree(), 'inDegree test failed for node 0 with 2 arcs'); $this->assertEquals(1, $node[1]->inDegree(), 'inDegree test failed for node 1 with 2 arcs'); $this->assertEquals(1, $node[2]->inDegree(), 'inDegree test failed for node 2 with 2 arcs'); $this->assertEquals(2, $node[0]->outDegree(), 'outDegree test failed for node 0 with 2 arcs'); $this->assertEquals(1, $node[1]->outDegree(), 'outDegree test failed for node 1 with 2 arcs'); $this->assertEquals(1, $node[2]->outDegree(), 'outDegree test failed for node 2 with 2 arcs'); } } ?> PK! ;VV5pear/Structures_Graph/tests/TopologicalSorterTest.phpnu[setData($name1); $graph->addNode($node1); $name11 = 'node11'; $node11 = new Structures_Graph_Node(); $node11->setData($name11); $graph->addNode($node11); $node1->connectTo($node11); $name12 = 'node12'; $node12 = new Structures_Graph_Node(); $node12->setData($name12); $graph->addNode($node12); $node1->connectTo($node12); $name121 = 'node121'; $node121 = new Structures_Graph_Node(); $node121->setData($name121); $graph->addNode($node121); $node12->connectTo($node121); $name2 = 'node2'; $node2 = new Structures_Graph_Node(); $node2->setData($name2); $graph->addNode($node2); $name21 = 'node21'; $node21 = new Structures_Graph_Node(); $node21->setData($name21); $graph->addNode($node21); $node2->connectTo($node21); $nodes = Structures_Graph_Manipulator_TopologicalSorter::sort($graph); $this->assertCount(2, $nodes[0]); $this->assertEquals('node1', $nodes[0][0]->getData()); $this->assertEquals('node2', $nodes[0][1]->getData()); $this->assertCount(3, $nodes[1]); $this->assertEquals('node11', $nodes[1][0]->getData()); $this->assertEquals('node12', $nodes[1][1]->getData()); $this->assertEquals('node21', $nodes[1][2]->getData()); $this->assertCount(1, $nodes[2]); $this->assertEquals('node121', $nodes[2][0]->getData()); } } ?> PK!e/pear/Structures_Graph/tests/AcyclicTestTest.phpnu[addNode($node1); $node2 = new Structures_Graph_Node(); $graph->addNode($node2); $node1->connectTo($node2); $node3 = new Structures_Graph_Node(); $graph->addNode($node3); $node2->connectTo($node3); $node3->connectTo($node1); $this->assertFalse( Structures_Graph_Manipulator_AcyclicTest::isAcyclic($graph), 'Graph is cyclic' ); } public function testIsAcyclicTrue() { $graph = new Structures_Graph(); $node1 = new Structures_Graph_Node(); $graph->addNode($node1); $node2 = new Structures_Graph_Node(); $graph->addNode($node2); $node1->connectTo($node2); $node3 = new Structures_Graph_Node(); $graph->addNode($node3); $node2->connectTo($node3); $this->assertTrue( Structures_Graph_Manipulator_AcyclicTest::isAcyclic($graph), 'Graph is acyclic' ); } } ?> PK!5htt&pear/Structures_Graph/tests/helper.incnu[ $d) { if ($i++ > 0) { print ", "; } print $d[0] . '=' . $d[1]; } print "\n"; print "params: " . implode(", ", $non_opts) . "\n"; print "\n"; } test("-abc", "abc"); test("-abc foo", "abc"); test("-abc foo", "abc:"); test("-abc foo bar gazonk", "abc"); test("-abc foo bar gazonk", "abc:"); test("-a -b -c", "abc"); test("-a -b -c", "abc:"); test("-abc", "ab:c"); test("-abc foo -bar gazonk", "abc"); ?> --EXPECT-- options: a=, b=, c= params: options: a=, b=, c= params: foo options: a=, b=, c=foo params: options: a=, b=, c= params: foo, bar, gazonk options: a=, b=, c=foo params: bar, gazonk options: a=, b=, c= params: Console_Getopt: option requires an argument --c options: a=, b=c params: options: a=, b=, c= params: foo, -bar, gazonk PK!'pear/Console_Getopt/tests/bug11068.phptnu[--TEST-- Console_Getopt [bug 11068] --SKIPIF-- --FILE-- getMessage()."\n"; echo 'FATAL'; exit; } print_r($ret); ?> --EXPECT-- Array ( [0] => Array ( [0] => Array ( [0] => f [1] => jjohnston@mail.com ) [1] => Array ( [0] => --to [1] => hi ) ) [1] => Array ( [0] => - ) )PK!'pear/Console_Getopt/tests/bug10557.phptnu[--TEST-- Console_Getopt [bug 10557] --SKIPIF-- --FILE-- getMessage()."\n"; echo 'FATAL'; exit; } print_r($ret); ?> --EXPECT-- Console_Getopt: option requires an argument --to FATALPK!|EE'pear/Console_Getopt/tests/bug13140.phptnu[--TEST-- Console_Getopt [bug 13140] --SKIPIF-- --FILE-- getopt2($cg->readPHPArgv(), 't', array('test'), true)); print_r($cg->getopt2($cg->readPHPArgv(), 'bar', array('foo'), true)); ?> --EXPECT-- Array ( [0] => Array ( [0] => Array ( [0] => --test [1] => ) ) [1] => Array ( [0] => thisshouldbehere ) ) Array ( [0] => Array ( [0] => Array ( [0] => --foo [1] => ) [1] => Array ( [0] => b [1] => ) [2] => Array ( [0] => a [1] => ) [3] => Array ( [0] => r [1] => ) [4] => Array ( [0] => r [1] => ) ) [1] => Array ( [0] => thisshouldbehere ) ) PK!e>44/pear/XML_Util/tests/CreateTagFromArrayTests.phpnu[ "foo:bar", ); $expected = ""; $this->assertEquals($expected, XML_Util::createTagFromArray($original)); } /** * @covers XML_Util::createTagFromArray() */ public function testCreateTagFromArrayWithQnameAndNamespace() { $original = array( "qname" => "foo:bar", "namespaceUri" => "http://foo.com", ); $expected = ""; $this->assertEquals($expected, XML_Util::createTagFromArray($original)); } /** * @covers XML_Util::createTagFromArray() */ public function testCreateTagFromArrayWithQnameAndNamespaceAndAttributes() { $original = array( "qname" => "foo:bar", "namespaceUri" => "http://foo.com", "attributes" => array( "key" => "value", "argh" => "fruit&vegetable" ), ); $expected = ""; $this->assertEquals($expected, XML_Util::createTagFromArray($original)); } /** * @covers XML_Util::createTagFromArray() */ public function testCreateTagFromArrayWithQnameAndNamespaceAndAttributesAndContent() { $original = array( "qname" => "foo:bar", "namespaceUri" => "http://foo.com", "attributes" => array( "key" => "value", "argh" => "fruit&vegetable" ), "content" => "I'm inside the tag", ); $expected = "I'm inside the tag"; $this->assertEquals($expected, XML_Util::createTagFromArray($original)); } /** * @covers XML_Util::createTagFromArray() */ public function testCreateTagFromArrayWithQnameAndAttributesAndContent() { $original = array( "qname" => "foo:bar", "attributes" => array( "key" => "value", "argh" => "fruit&vegetable" ), "content" => "I'm inside the tag", ); $expected = "I'm inside the tag"; $this->assertEquals($expected, XML_Util::createTagFromArray($original)); } /** * @covers XML_Util::createTagFromArray() */ public function testCreateTagFromArrayWithQnameAndNamespaceAndContent() { $original = array( "qname" => "foo:bar", "namespaceUri" => "http://foo.com", "content" => "I'm inside the tag", ); $expected = "I'm inside the tag"; $this->assertEquals($expected, XML_Util::createTagFromArray($original)); } /** * @covers XML_Util::createTagFromArray() */ public function testCreateTagFromArrayWithQnameAndNamespaceAndAttributesAndContentWithEntitiesNone() { $original = array( "qname" => "foo:bar", "namespaceUri" => "http://foo.com", "attributes" => array( "key" => "value", "argh" => "fruit&vegetable" ), "content" => "I'm inside the tag", ); $expected = "I'm inside the tag"; $this->assertEquals($expected, XML_Util::createTagFromArray($original, XML_UTIL_ENTITIES_NONE)); } /** * @covers XML_Util::createTagFromArray() */ public function testCreateTagFromArrayWithQnameAndNamespaceAndAttributesAndContentWithReplaceEntities() { $original = array( "qname" => "foo:bar", "namespaceUri" => "http://foo.com", "attributes" => array( "key" => "value", "argh" => "fruit&vegetable" ), "content" => "I'm inside the tag", ); $expected = "I'm inside the tag"; $this->assertEquals($expected, XML_Util::createTagFromArray($original, XML_UTIL_REPLACE_ENTITIES)); } /** * @covers XML_Util::createTagFromArray() */ public function testCreateTagFromArrayWithQnameAndNamespaceAndAttributesAndContentWithReplaceEntitiesAndMultilineFalse() { $original = array( "qname" => "foo:bar", "namespaceUri" => "http://foo.com", "attributes" => array( "key" => "value", "argh" => "fruit&vegetable" ), "content" => "I'm inside the tag", ); $multiline = false; $expected = "I'm inside the tag"; $this->assertEquals($expected, XML_Util::createTagFromArray($original, XML_UTIL_REPLACE_ENTITIES, $multiline)); } /** * @covers XML_Util::createTagFromArray() */ public function testCreateTagFromArrayWithQnameAndNamespaceAndAttributesAndContentWithReplaceEntitiesAndMultilineTrue() { $original = array( "qname" => "foo:bar", "namespaceUri" => "http://foo.com", "attributes" => array( "key" => "value", "argh" => "fruit&vegetable" ), "content" => "I'm inside the tag", ); $multiline = true; $expected = <<< EOF I'm inside the tag EOF; $this->assertEquals($expected, XML_Util::createTagFromArray($original, XML_UTIL_REPLACE_ENTITIES, $multiline)); } /** * @covers XML_Util::createTagFromArray() */ public function testCreateTagFromArrayWithQnameAndNamespaceAndAttributesAndContentWithReplaceEntitiesAndMultilineTrueAndIndent() { $original = array( "qname" => "foo:bar", "namespaceUri" => "http://foo.com", "attributes" => array( "key" => "value", "argh" => "fruit&vegetable" ), "content" => "I'm inside the tag", ); $multiline = true; $indent = " "; $expected = <<< EOF I'm inside the tag EOF; $this->assertEquals($expected, XML_Util::createTagFromArray($original, XML_UTIL_REPLACE_ENTITIES, $multiline, $indent)); } /** * @covers XML_Util::createTagFromArray() */ public function testCreateTagFromArrayWithQnameAndNamespaceAndAttributesAndContentWithReplaceEntitiesAndMultilineTrueAndIndentAndLinebreak() { $original = array( "qname" => "foo:bar", "namespaceUri" => "http://foo.com", "attributes" => array( "key" => "value", "argh" => "fruit&vegetable" ), "content" => "I'm inside the tag", ); $multiline = true; $indent = " "; $linebreak = "^"; $expected = "I'm inside the tag"; $this->assertEquals($expected, XML_Util::createTagFromArray($original, XML_UTIL_REPLACE_ENTITIES, $multiline, $indent, $linebreak)); } /** * @covers XML_Util::createTagFromArray() */ public function testCreateTagFromArrayWithQnameAndNamespaceAndAttributesAndContentWithReplaceEntitiesAndMultilineTrueAndIndentAndLinebreakAndSortAttributesTrue() { $original = array( "qname" => "foo:bar", "namespaceUri" => "http://foo.com", "attributes" => array( "key" => "value", "argh" => "fruit&vegetable" ), "content" => "I'm inside the tag", ); $multiline = true; $indent = " "; $linebreak = "^"; $sortAttributes = true; $expected = "I'm inside the tag"; $this->assertEquals($expected, XML_Util::createTagFromArray($original, XML_UTIL_REPLACE_ENTITIES, $multiline, $indent, $linebreak, $sortAttributes)); } /** * @covers XML_Util::createTagFromArray() */ public function testCreateTagFromArrayWithQnameAndNamespaceAndAttributesAndContentWithReplaceEntitiesAndMultilineTrueAndIndentAndLinebreakAndSortAttributesFalse() { $original = array( "qname" => "foo:bar", "namespaceUri" => "http://foo.com", "attributes" => array( "key" => "value", "argh" => "fruit&vegetable" ), "content" => "I'm inside the tag", ); $multiline = true; $indent = " "; $linebreak = "^"; $sortAttributes = false; $expected = "I'm inside the tag"; $this->assertEquals($expected, XML_Util::createTagFromArray($original, XML_UTIL_REPLACE_ENTITIES, $multiline, $indent, $linebreak, $sortAttributes)); } /** * @covers XML_Util::createTagFromArray() */ public function testCreateTagFromArrayWithInvalidArray() { $badArray = array( "foo" => "bar", ); $expectedError = "You must either supply a qualified name (qname) or local tag name (localPart)."; $this->assertEquals($expectedError, XML_Util::createTagFromArray($badArray)); } /** * @covers XML_Util::createTagFromArray() */ public function testCreateTagFromArrayWithNamespaceAndAttributesAndContentButWithoutQname() { $original = array( "namespaceUri" => "http://foo.com", "attributes" => array( "key" => "value", "argh" => "fruit&vegetable" ), "content" => "I'm inside the tag", ); $expectedError = "You must either supply a qualified name (qname) or local tag name (localPart)."; $this->assertEquals($expectedError, XML_Util::createTagFromArray($original)); } /** * @covers XML_Util::createTagFromArray() */ public function testCreateTagFromArrayWithNonScalarContent() { $badArray = array( 'content' => array('foo', 'bar'), ); $expectedError = "Supplied non-scalar value as tag content"; $this->assertEquals($expectedError, XML_Util::createTagFromArray($badArray)); } /** * @covers XML_Util::createTagFromArray() */ public function testCreateTagFromArrayWithArrayOfNamespaces() { $original = array( 'qname' => 'foo:bar', 'namespaces' => array('ns1' => 'uri1', 'ns2' => 'uri2'), ); $expected = ""; $this->assertEquals($expected, XML_Util::createTagFromArray($original)); } /** * @covers XML_Util::createTagFromArray() */ public function testCreateTagFromArrayWithQnameDerivedFromNamespaceUriAndLocalPart() { $original = array( 'namespaceUri' => 'http://bar.org', 'localPart' => 'foo' ); $expected = ""; $this->assertEquals($expected, XML_Util::createTagFromArray($original)); } /** * @covers XML_Util::createTagFromArray() */ public function testCreateTagFromArrayWithQnameDerivedFromNamespaceAndLocalPart() { $original = array( 'namespace' => 'http://foo.org', 'localPart' => 'bar' ); $expected = ""; $this->assertEquals($expected, XML_Util::createTagFromArray($original)); } /** * @covers XML_Util::createTagFromArray() */ public function testCreateTagFromArrayWithQnameDerivedFromLocalPart() { $original = array( 'namespace' => '', 'localPart' => 'bar' ); $expected = ""; $this->assertEquals($expected, XML_Util::createTagFromArray($original)); } /** * @covers XML_Util::createTagFromArray() */ public function testCreateTagFromArrayWithImplicitlyEmptyContentAndCollapseNoneDoesNotCollapseTag() { $original = array('qname' => 'tag1'); $expected = ""; $actual = XML_Util::createTagFromArray( $original, XML_UTIL_REPLACE_ENTITIES, // default $replaceEntities false, // default $multiline '_auto', // default $indent "\n", // default $linebreak true, // default $sortAttributes XML_UTIL_COLLAPSE_NONE ); $this->assertEquals($expected, $actual); } /** * @covers XML_Util::createTagFromArray() */ public function testCreateTagFromArrayForCdataWithExplicitlyEmptyContentDoesNotCollapseTag() { $original = array('qname' => 'tag1', 'content' => ''); $expected = ""; $this->assertEquals($expected, XML_Util::createTagFromArray($original, XML_UTIL_CDATA_SECTION)); } } PK!C,pear/XML_Util/tests/ReplaceEntitiesTests.phpnu[.'; } protected function getUtf8Data() { return 'This data contains special chars like <, >, & and " as well as ä, ö, ß, à and ê'; } /** * @covers XML_Util::replaceEntities() */ public function testReplaceEntitiesForSimpleData() { $expected = "This string contains < & >."; $this->assertEquals($expected, XML_Util::replaceEntities($this->getSimpleData())); } /** * @covers XML_Util::replaceEntities() */ public function testReplaceEntitiesForSimpleDataWithInvalidOptionReturnsOriginalData() { $expected = "This string contains < & >."; $this->assertEquals($expected, XML_Util::replaceEntities($this->getSimpleData(), 'INVALID_OPTION')); } /** * @covers XML_Util::replaceEntities() */ public function testReplaceEntitiesForSimpleDataWithEntitiesXml() { $expected = "This string contains < & >."; $this->assertEquals($expected, XML_Util::replaceEntities($this->getSimpleData(), XML_UTIL_ENTITIES_XML)); } /** * @covers XML_Util::replaceEntities() */ public function testReplaceEntitiesForSimpleDataWithEntitiesXmlAndEncoding() { $encoding = "UTF-8"; $expected = "This string contains < & >."; $this->assertEquals($expected, XML_Util::replaceEntities($this->getSimpleData(), XML_UTIL_ENTITIES_XML, $encoding)); } /** * @covers XML_Util::replaceEntities() */ public function testReplaceEntitiesForUtf8DataWithEntitiesXmlAndEncoding() { $encoding = "UTF-8"; $expected = "This data contains special chars like <, >, & and " as well as ä, ö, ß, à and ê"; $this->assertEquals($expected, XML_Util::replaceEntities($this->getUtf8Data(), XML_UTIL_ENTITIES_XML, $encoding)); } /** * @covers XML_Util::replaceEntities() */ public function testReplaceEntitiesForSimpleDataWithEntitiesXmlRequired() { $expected = "This string contains < & >."; $this->assertEquals($expected, XML_Util::replaceEntities($this->getSimpleData(), XML_UTIL_ENTITIES_XML_REQUIRED)); } /** * @covers XML_Util::replaceEntities() */ public function testReplaceEntitiesForSimpleDataWithEntitiesXmlRequiredAndEncoding() { $encoding = "UTF-8"; $expected = "This string contains < & >."; $this->assertEquals($expected, XML_Util::replaceEntities($this->getSimpleData(), XML_UTIL_ENTITIES_XML_REQUIRED, $encoding)); } /** * @covers XML_Util::replaceEntities() */ public function testReplaceEntitiesForUtf8DataWithEntitiesXmlRequiredAndEncoding() { $encoding = "UTF-8"; $expected = "This data contains special chars like <, >, & and " as well as ä, ö, ß, à and ê"; $this->assertEquals($expected, XML_Util::replaceEntities($this->getUtf8Data(), XML_UTIL_ENTITIES_XML_REQUIRED, $encoding)); } /** * @covers XML_Util::replaceEntities() */ public function testReplaceEntitiesForSimpleDataWithEntitiesHtml() { $expected = "This string contains < & >."; $this->assertEquals($expected, XML_Util::replaceEntities($this->getSimpleData(), XML_UTIL_ENTITIES_HTML)); } /** * @covers XML_Util::replaceEntities() */ public function testReplaceEntitiesForSimpleDataWithEntitiesHtmlAndEncoding() { $encoding = "UTF-8"; $expected = "This string contains < & >."; $this->assertEquals($expected, XML_Util::replaceEntities($this->getSimpleData(), XML_UTIL_ENTITIES_HTML, $encoding)); } /** * @covers XML_Util::replaceEntities() */ public function testReplaceEntitiesForUtf8DataWithEntitiesHtmlAndEncoding() { $encoding = "UTF-8"; $expected = "This data contains special chars like <, >, & and " as well as ä, ö, ß, à and ê"; $this->assertEquals($expected, XML_Util::replaceEntities($this->getUtf8Data(), XML_UTIL_ENTITIES_HTML, $encoding)); } } PK!یu'pear/XML_Util/tests/ApiVersionTests.phpnu[assertEquals('1.4', XML_Util::apiVersion()); } }PK!Gs$pear/XML_Util/tests/Bug5392Tests.phpnu[, & and " as well as ä, ö, ß, à and ê'; $replacedResult = XML_Util::replaceEntities($original, XML_UTIL_ENTITIES_HTML, "UTF-8"); $reversedResult = XML_Util::reverseEntities($replacedResult, XML_UTIL_ENTITIES_HTML, "UTF-8"); $this->assertEquals($original, $reversedResult, "Failed bugcheck."); } } PK!4ejj/pear/XML_Util/tests/CreateCDataSectionTests.phpnu["; $this->assertEquals($expected, XML_Util::createCDataSection($original)); } } PK!|\5.pear/XML_Util/tests/CollapseEmptyTagsTests.phpnu["; $expected = ""; $this->assertEquals($expected, XML_Util::collapseEmptyTags($emptyTag)); } /** * @covers XML_Util::collapseEmptyTags() */ public function testCollapseEmptyTagsBasicUsageAlongsideNonemptyTag() { $emptyTag = ""; $otherTag = "baz"; $expected = "baz"; $this->assertEquals($expected, XML_Util::collapseEmptyTags($emptyTag . $otherTag)); } /** * @covers XML_Util::collapseEmptyTags() */ public function testCollapseEmptyTagsOnOneEmptyTagWithCollapseAll() { $emptyTag = ""; $expected = ""; $this->assertEquals($expected, XML_Util::collapseEmptyTags($emptyTag, XML_UTIL_COLLAPSE_ALL)); } /** * @covers XML_Util::collapseEmptyTags() */ public function testCollapseEmptyTagsOnOneEmptyTagAlongsideNonemptyTagWithCollapseAll() { $emptyTag = ""; $otherTag = "baz"; $expected = "baz"; $this->assertEquals($expected, XML_Util::collapseEmptyTags($emptyTag . $otherTag, XML_UTIL_COLLAPSE_ALL)); } /** * @covers XML_Util::collapseEmptyTags() */ public function testCollapseEmptyTagsOnOneEmptyTagAlongsideNonemptyTagAlongsideEmptyTagWithCollapseAll() { $emptyTag = ""; $otherTag = "baz"; $expected = "baz"; $this->assertEquals($expected, XML_Util::collapseEmptyTags($emptyTag . $otherTag . $emptyTag, XML_UTIL_COLLAPSE_ALL)); } /** * @covers XML_Util::collapseEmptyTags() */ public function testCollapseEmptyTagsOnOneEmptyPrefixedTagAlongsideNonemptyTagAlongsideEmptyPrefixedTagWithCollapseAll() { $emptyTag = ""; $otherTag = "baz"; $expected = "baz"; $this->assertEquals($expected, XML_Util::collapseEmptyTags($emptyTag . $otherTag . $emptyTag, XML_UTIL_COLLAPSE_ALL)); } /** * @covers XML_Util::collapseEmptyTags() */ public function testCollapseEmptyTagsOnOneEmptyNsPrefixedTagAlongsideNonemptyTagAlongsideEmptyNsPrefixedTagWithCollapseAll() { $emptyTag = ""; $otherTag = "baz"; $expected = "baz"; $this->assertEquals($expected, XML_Util::collapseEmptyTags($emptyTag . $otherTag . $emptyTag, XML_UTIL_COLLAPSE_ALL)); } /** * @covers XML_Util::collapseEmptyTags() */ public function testCollapseEmptyTagsOnOneEmptyTagWithCollapseXhtml() { $emptyTag = ""; $expected = ""; $this->assertEquals($expected, XML_Util::collapseEmptyTags($emptyTag, XML_UTIL_COLLAPSE_XHTML_ONLY)); } /** * @covers XML_Util::collapseEmptyTags() */ public function testCollapseEmptyTagsOnOneEmptyTagAlongsideNonemptyTagWithCollapseXhtml() { $emptyTag = ""; $otherTag = "baz"; $xhtmlTag = "

"; $expected = "
baz"; $this->assertEquals($expected, XML_Util::collapseEmptyTags($emptyTag . $xhtmlTag . $otherTag, XML_UTIL_COLLAPSE_XHTML_ONLY)); } /** * @covers XML_Util::collapseEmptyTags() */ public function testCollapseEmptyTagsOnOneEmptyTagWithCollapseNone() { $emptyTag = ""; $expected = ""; $this->assertEquals($expected, XML_Util::collapseEmptyTags($emptyTag, XML_UTIL_COLLAPSE_NONE)); } /** * @covers XML_Util::collapseEmptyTags() */ public function testCollapseEmptyTagsOnOneEmptyTagAlongsideNonemptyTagWithCollapseNone() { $emptyTag = ""; $otherTag = "baz"; $expected = "baz"; $this->assertEquals($expected, XML_Util::collapseEmptyTags($emptyTag . $otherTag, XML_UTIL_COLLAPSE_NONE)); } } PK!GG/pear/XML_Util/tests/SplitQualifiedNameTests.phpnu[ 'xslt', 'localPart' => 'stylesheet', ); $this->assertEquals($expected, XML_Util::splitQualifiedName($original)); } /** * @covers XML_Util::splitQualifiedName() */ public function testSplitQualifiedNameWithNamespace() { $original = "stylesheet"; $namespace = "myNs"; $expected = array( 'namespace' => 'myNs', 'localPart' => 'stylesheet', ); $this->assertEquals($expected, XML_Util::splitQualifiedName($original, $namespace)); } } PK!Yq%pear/XML_Util/tests/Bug21184Tests.phpnu[one'; $this->assertEquals($xml, XML_Util::collapseEmptyTags($xml, XML_UTIL_COLLAPSE_ALL)); } } PK!>M$pear/XML_Util/tests/Bug4950Tests.phpnu[ here!"; $namespaceUrl = null; $expected = " here!]]>"; $result = XML_Util::createTag($qname, $attributes, $content, $namespaceUrl, XML_UTIL_CDATA_SECTION); $this->assertEquals($expected, $result, "Failed bugcheck."); } } PK!YR""/pear/XML_Util/tests/CreateStartElementTests.phpnu["; $this->assertEquals($expected, XML_Util::createStartElement($original)); } /** * @covers XML_Util::createStartElement() */ public function testCreateStartElementForTagWithAttributes() { $originalTag = "myNs:myTag"; $originalAttributes = array("foo" => "bar"); $expected = ""; $this->assertEquals($expected, XML_Util::createStartElement($originalTag, $originalAttributes)); } /** * @covers XML_Util::createStartElement() */ public function testCreateStartElementForTagWithEmptyAttributes() { $originalTag = "myNs:myTag"; $originalAttributes = ""; $expected = ""; $this->assertEquals($expected, XML_Util::createStartElement($originalTag, $originalAttributes)); } /** * @covers XML_Util::createStartElement() */ public function testCreateStartElementForTagWithAttributesAndNamespace() { $originalTag = "myNs:myTag"; $originalAttributes = array("foo" => "bar"); $originalNamespace = "http://www.w3c.org/myNs#"; $expected = ""; $this->assertEquals($expected, XML_Util::createStartElement($originalTag, $originalAttributes, $originalNamespace)); } /** * @covers XML_Util::createStartElement() */ public function testCreateStartElementForTagWithEmptyAttributesAndNonUriNamespace() { $originalTag = "myTag"; $originalAttributes = ""; $originalNamespace = "foo"; $expected = ""; $this->assertEquals($expected, XML_Util::createStartElement($originalTag, $originalAttributes, $originalNamespace)); } /** * @covers XML_Util::createStartElement() */ public function testCreateStartElementForTagWithAttributesAndNamespaceWithMultiline() { $originalTag = "myNs:myTag"; $originalAttributes = array("foo" => "bar"); $originalNamespace = "http://www.w3c.org/myNs#"; $expected = <<< EOF EOF; $multiline = true; $this->assertEquals($expected, XML_Util::createStartElement($originalTag, $originalAttributes, $originalNamespace, $multiline)); } /** * @covers XML_Util::createStartElement() */ public function testCreateStartElementForTagWithAttributesAndNamespaceWithMultilineAndIndent() { $originalTag = "myNs:myTag"; $originalAttributes = array("foo" => "bar"); $originalNamespace = "http://www.w3c.org/myNs#"; $expected = <<< EOF EOF; $multiline = true; $indent = " "; $this->assertEquals($expected, XML_Util::createStartElement($originalTag, $originalAttributes, $originalNamespace, $multiline, $indent)); } /** * @covers XML_Util::createStartElement() */ public function testCreateStartElementForTagWithAttributesAndNamespaceWithMultilineAndIndentAndLinebreak() { $originalTag = "myNs:myTag"; $originalAttributes = array("foo" => "bar"); $originalNamespace = "http://www.w3c.org/myNs#"; $expected = ""; $multiline = true; $indent = " "; $linebreak = "^"; $this->assertEquals($expected, XML_Util::createStartElement($originalTag, $originalAttributes, $originalNamespace, $multiline, $indent, $linebreak)); } /** * @covers XML_Util::createStartElement() */ public function testCreateStartElementForTagWithAttributesAndNamespaceWithMultilineAndIndentAndLinebreakAndSortAttributesIsTrue() { $originalTag = "myNs:myTag"; $originalAttributes = array("foo" => "bar", "boo" => "baz"); $originalNamespace = "http://www.w3c.org/myNs#"; $expected = ""; $multiline = true; $indent = " "; $linebreak = "^"; $sortAttributes = true; $this->assertEquals($expected, XML_Util::createStartElement($originalTag, $originalAttributes, $originalNamespace, $multiline, $indent, $linebreak, $sortAttributes)); } /** * @covers XML_Util::createStartElement() */ public function testCreateStartElementForTagWithAttributesAndNamespaceWithMultilineAndIndentAndLinebreakAndSortAttributesIsFalse() { $originalTag = "myNs:myTag"; $originalAttributes = array("foo" => "bar", "boo" => "baz"); $originalNamespace = "http://www.w3c.org/myNs#"; $expected = ""; $multiline = true; $indent = " "; $linebreak = "^"; $sortAttributes = false; $this->assertEquals($expected, XML_Util::createStartElement($originalTag, $originalAttributes, $originalNamespace, $multiline, $indent, $linebreak, $sortAttributes)); } } PK!ܬ$2pear/XML_Util/tests/GetDocTypeDeclarationTests.phpnu["; $this->assertEquals($expected, XML_Util::getDocTypeDeclaration("rootTag")); } /** * @covers XML_Util::getDocTypeDeclaration() */ public function testGetDocTypeDeclarationUsingRootAndStringUri() { $expected = ""; $this->assertEquals($expected, XML_Util::getDocTypeDeclaration("rootTag", "myDocType.dtd")); } /** * @covers XML_Util::getDocTypeDeclaration() */ public function testGetDocTypeDeclarationUsingRootAndArrayUri() { $uri = array( 'uri' => 'http://pear.php.net/dtd/package-1.0', 'id' => '-//PHP//PEAR/DTD PACKAGE 0.1' ); $expected = ""; $this->assertEquals($expected, XML_Util::getDocTypeDeclaration("rootTag", $uri)); } /** * @covers XML_Util::getDocTypeDeclaration() */ public function testGetDocTypeDeclarationUsingRootAndArrayUriAndInternalDtd() { $uri = array( 'uri' => 'http://pear.php.net/dtd/package-1.0', 'id' => '-//PHP//PEAR/DTD PACKAGE 0.1' ); $dtdEntry = ''; $expected = <<< EOF ]> EOF; $this->assertEquals($expected, XML_Util::getDocTypeDeclaration("rootTag", $uri, $dtdEntry)); } } PK!G%pear/XML_Util/tests/Bug21177Tests.phpnu['; return array( array('', ''), array('', ''), array('', ''), array('', ''), ); } /** * @dataProvider getTestCandidate() */ public function testCollapseEmptyTagsForBug21177($original, $expected) { $this->assertEquals($expected, XML_Util::collapseEmptyTags($original, XML_UTIL_COLLAPSE_ALL), "Failed bugcheck."); } } PK!۩%pear/XML_Util/tests/Bug18343Tests.phpnu[ "install", "attributes" => array( "as" => "Horde/Feed/fixtures/lexicon/http-p.moreover.com-cgi-local-page%2Fo=rss&s=Newsweek", "name" => "test/Horde/Feed/fixtures/lexicon/http-p.moreover.com-cgi-local-page%2Fo=rss&s=Newsweek", ) ); public function getFlagsToTest() { new XML_Util(); // for constants to be declared return array( array('no flag', null), array('false', false), array('ENTITIES_NONE', XML_UTIL_ENTITIES_NONE), array('ENTITIES_XML', XML_UTIL_ENTITIES_XML), array('ENTITIES_XML_REQUIRED', XML_UTIL_ENTITIES_XML_REQUIRED), array('ENTITIES_HTML', XML_UTIL_ENTITIES_HTML), array('REPLACE_ENTITIES', XML_UTIL_REPLACE_ENTITIES), ); } /** * @dataProvider getFlagsToTest() */ public function testCreateTagFromArrayForBug18343($key, $flag) { // all flags for the candidate input should return the same result $expected = <<< EOF EOF; $this->assertEquals($expected, XML_Util::createTagFromArray($this->tagArray, $flag), "Failed bugcheck for $key."); } } PK!zt,pear/XML_Util/tests/ReverseEntitiesTests.phpnu[."; $this->assertEquals($expected, XML_Util::reverseEntities($this->getSimpleData())); } /** * @covers XML_Util::reverseEntities() */ public function testReverseEntitiesForSimpleDataWithInvalidOptionReturnsOriginalData() { $expected = "This string contains < & >."; $this->assertEquals($expected, XML_Util::reverseEntities($this->getSimpleData(), 'INVALID_OPTION')); } /** * @covers XML_Util::reverseEntities() */ public function testReverseEntitiesForSimpleDataWithEntitiesXml() { $expected = "This string contains < & >."; $this->assertEquals($expected, XML_Util::reverseEntities($this->getSimpleData(), XML_UTIL_ENTITIES_XML)); } /** * @covers XML_Util::reverseEntities() */ public function testReverseEntitiesForSimpleDataWithEntitiesXmlAndEncoding() { $encoding = "UTF-8"; $expected = "This string contains < & >."; $this->assertEquals($expected, XML_Util::reverseEntities($this->getSimpleData(), XML_UTIL_ENTITIES_XML), $encoding); } /** * @covers XML_Util::reverseEntities() */ public function testReverseEntitiesForUtf8DataWithEntitiesXmlAndEncoding() { $encoding = "UTF-8"; $expected = "This data contains special chars like <, >, & and \" as well as ä, ö, ß, à and ê"; $this->assertEquals($expected, XML_Util::reverseEntities($this->getUtf8Data(), XML_UTIL_ENTITIES_XML), $encoding); } /** * @covers XML_Util::reverseEntities() */ public function testReverseEntitiesForSimpleDataWithEntitiesXmlRequired() { $expected = "This string contains < & >."; $this->assertEquals($expected, XML_Util::reverseEntities($this->getSimpleData(), XML_UTIL_ENTITIES_XML_REQUIRED)); } /** * @covers XML_Util::reverseEntities() */ public function testReverseEntitiesForSimpleDataWithEntitiesXmlRequiredAndEncoding() { $encoding = "UTF-8"; $expected = "This string contains < & >."; $this->assertEquals($expected, XML_Util::reverseEntities($this->getSimpleData(), XML_UTIL_ENTITIES_XML_REQUIRED, $encoding)); } /** * @covers XML_Util::reverseEntities() */ public function testReverseEntitiesForUtf8DataWithEntitiesXmlRequiredAndEncoding() { $encoding = "UTF-8"; $expected = "This data contains special chars like <, >, & and \" as well as ä, ö, ß, à and ê"; $this->assertEquals($expected, XML_Util::reverseEntities($this->getUtf8Data(), XML_UTIL_ENTITIES_XML_REQUIRED, $encoding)); } /** * @covers XML_Util::reverseEntities() */ public function testReverseEntitiesForSimpleDataWithEntitiesHtml() { $expected = "This string contains < & >."; $this->assertEquals($expected, XML_Util::reverseEntities($this->getSimpleData(), XML_UTIL_ENTITIES_HTML)); } /** * @covers XML_Util::reverseEntities() */ public function testReverseEntitiesForSimpleDataWithEntitiesHtmlAndEncoding() { $encoding = "UTF-8"; $expected = "This string contains < & >."; $this->assertEquals($expected, XML_Util::reverseEntities($this->getSimpleData(), XML_UTIL_ENTITIES_HTML, $encoding)); } /** * @covers XML_Util::reverseEntities() */ public function testReverseEntitiesForUtf8DataWithEntitiesHtmlAndEncoding() { $encoding = "UTF-8"; $expected = "This data contains special chars like <, >, & and \" as well as ä, ö, ß, à and ê"; $this->assertEquals($expected, XML_Util::reverseEntities($this->getUtf8Data(), XML_UTIL_ENTITIES_HTML, $encoding)); } } PK!~$[ee-pear/XML_Util/tests/CreateEndElementTests.phpnu["; $this->assertEquals($expected, XML_Util::createEndElement($original)); } /** * @covers XML_Util::createEndElement() */ public function testCreateEndElementWithNamespacedTag() { $original = "myNs:myTag"; $expected = ""; $this->assertEquals($expected, XML_Util::createEndElement($original)); } } PK!!)pear/XML_Util/tests/AbstractUnitTests.phpnu[ "bar"); $expected = ""; $this->assertEquals($expected, XML_Util::createTag($originalTag, $originalAttributes)); } /** * @covers XML_Util::createTag() */ public function testCreateTagForTagWithAttributesAndContent() { $originalTag = "myNs:myTag"; $originalAttributes = array("foo" => "bar"); $originalContent = "This is inside the tag"; $expected = "This is inside the tag"; $this->assertEquals($expected, XML_Util::createTag($originalTag, $originalAttributes, $originalContent)); } /** * @covers XML_Util::createTag() */ public function testCreateTagForTagWithAttributesAndContentAndNamespace() { $originalTag = "myNs:myTag"; $originalAttributes = array("foo" => "bar"); $originalContent = "This is inside the tag"; $originalNamespace = "http://www.w3c.org/myNs#"; $expected = "This is inside the tag"; $this->assertEquals($expected, XML_Util::createTag($originalTag, $originalAttributes, $originalContent, $originalNamespace)); } /** * @covers XML_Util::createTag() */ public function testCreateTagForTagWithAttributesAndContentAndNamespaceWithCDataSection() { $originalTag = "myNs:myTag"; $originalAttributes = array("foo" => "bar"); $originalContent = "This is inside the tag and has < & @ > in it"; $originalNamespace = "http://www.w3c.org/myNs#"; $expected = " in it]]>"; $this->assertEquals($expected, XML_Util::createTag($originalTag, $originalAttributes, $originalContent, $originalNamespace, XML_UTIL_CDATA_SECTION)); } /** * @covers XML_Util::createTag() */ public function testCreateTagForTagWithAttributesAndContentAndNamespaceWithReplaceEntities() { $originalTag = "myNs:myTag"; $originalAttributes = array("foo" => "bar"); $originalContent = "This is inside the tag and has < & @ > in it"; $originalNamespace = "http://www.w3c.org/myNs#"; $expected = "This is inside the tag and has < & @ > in it"; $this->assertEquals($expected, XML_Util::createTag($originalTag, $originalAttributes, $originalContent, $originalNamespace, XML_UTIL_REPLACE_ENTITIES)); } /** * @covers XML_Util::createTag() */ public function testCreateTagForTagWithAttributesAndContentAndNamespaceWithReplaceEntitiesAndMultilineFalse() { $originalTag = "myNs:myTag"; $originalAttributes = array("foo" => "bar"); $originalContent = "This is inside the tag and has < & @ > in it"; $originalNamespace = "http://www.w3c.org/myNs#"; $multiline = false; $expected = "This is inside the tag and has < & @ > in it"; $this->assertEquals($expected, XML_Util::createTag($originalTag, $originalAttributes, $originalContent, $originalNamespace, XML_UTIL_REPLACE_ENTITIES, $multiline)); } /** * @covers XML_Util::createTag() */ public function testCreateTagForTagWithAttributesAndContentAndNamespaceWithReplaceEntitiesAndMultilineTrue() { $originalTag = "myNs:myTag"; $originalAttributes = array("foo" => "bar"); $originalContent = "This is inside the tag and has < & @ > in it"; $originalNamespace = "http://www.w3c.org/myNs#"; $multiline = true; $expected = <<< EOF This is inside the tag and has < & @ > in it EOF; $this->assertEquals($expected, XML_Util::createTag($originalTag, $originalAttributes, $originalContent, $originalNamespace, XML_UTIL_REPLACE_ENTITIES, $multiline)); } /** * @covers XML_Util::createTag() */ public function testCreateTagForTagWithAttributesAndContentAndNamespaceWithReplaceEntitiesAndMultilineTrueAndIndent() { $originalTag = "myNs:myTag"; $originalAttributes = array("foo" => "bar"); $originalContent = "This is inside the tag and has < & @ > in it"; $originalNamespace = "http://www.w3c.org/myNs#"; $multiline = true; $indent = " "; $expected = <<< EOF This is inside the tag and has < & @ > in it EOF; $this->assertEquals($expected, XML_Util::createTag($originalTag, $originalAttributes, $originalContent, $originalNamespace, XML_UTIL_REPLACE_ENTITIES, $multiline, $indent)); } /** * @covers XML_Util::createTag() */ public function testCreateTagForTagWithAttributesAndContentAndNamespaceWithReplaceEntitiesAndMultilineTrueAndIndentAndLinebreak() { $originalTag = "myNs:myTag"; $originalAttributes = array("foo" => "bar"); $originalContent = "This is inside the tag and has < & @ > in it"; $originalNamespace = "http://www.w3c.org/myNs#"; $multiline = true; $indent = " "; $linebreak = "^"; $expected = "This is inside the tag and has < & @ > in it"; $this->assertEquals($expected, XML_Util::createTag($originalTag, $originalAttributes, $originalContent, $originalNamespace, XML_UTIL_REPLACE_ENTITIES, $multiline, $indent, $linebreak)); } /** * @covers XML_Util::createTag() */ public function testCreateTagForTagWithAttributesAndContentAndNamespaceWithReplaceEntitiesAndMultilineTrueAndIndentAndLinebreakAndSortAttributesTrue() { $originalTag = "myNs:myTag"; $originalAttributes = array("foo" => "bar", "boo" => "baz"); $originalContent = "This is inside the tag and has < & @ > in it"; $originalNamespace = "http://www.w3c.org/myNs#"; $multiline = true; $indent = " "; $linebreak = "^"; $sortAttributes = true; $expected = "This is inside the tag and has < & @ > in it"; $this->assertEquals($expected, XML_Util::createTag($originalTag, $originalAttributes, $originalContent, $originalNamespace, XML_UTIL_REPLACE_ENTITIES, $multiline, $indent, $linebreak, $sortAttributes)); } /** * @covers XML_Util::createTag() */ public function testCreateTagForTagWithAttributesAndContentAndNamespaceWithReplaceEntitiesAndMultilineTrueAndIndentAndLinebreakAndSortAttributesFalse() { $originalTag = "myNs:myTag"; $originalAttributes = array("foo" => "bar", "boo" => "baz"); $originalContent = "This is inside the tag and has < & @ > in it"; $originalNamespace = "http://www.w3c.org/myNs#"; $multiline = true; $indent = " "; $linebreak = "^"; $sortAttributes = false; $expected = "This is inside the tag and has < & @ > in it"; $this->assertEquals($expected, XML_Util::createTag($originalTag, $originalAttributes, $originalContent, $originalNamespace, XML_UTIL_REPLACE_ENTITIES, $multiline, $indent, $linebreak, $sortAttributes)); } } PK!Df:.pear/XML_Util/tests/GetXmlDeclarationTests.phpnu["; $this->assertEquals($expected, XML_Util::getXMLDeclaration($version)); } /** * @covers XML_Util::getXMLDeclaration() */ public function testGetXMLDeclarationUsingVersionAndEncodingAndStandalone() { $version = "1.0"; $encoding = "UTF-8"; $standalone = true; $expected = ""; $this->assertEquals($expected, XML_Util::getXMLDeclaration($version, $encoding, $standalone)); } /** * @covers XML_Util::getXMLDeclaration() */ public function testGetXMLDeclarationUsingVersionAndStandalone() { $version = "1.0"; $encoding = null; $standalone = true; $expected = ""; $this->assertEquals($expected, XML_Util::getXMLDeclaration($version, $encoding, $standalone)); } } PK!Zt/pear/XML_Util/tests/AttributesToStringTests.phpnu[ 'bar','boo' => 'baz',); $expected = " boo=\"baz\" foo=\"bar\""; $this->assertEquals($expected, XML_Util::attributesToString($original)); } /** * @covers XML_Util::attributesToString() */ public function testAttributesToStringWithExplicitSortTrue() { $original = array('foo' => 'bar','boo' => 'baz',); $expected = " boo=\"baz\" foo=\"bar\""; $sort = true; $this->assertEquals($expected, XML_Util::attributesToString($original, $sort)); } /** * @covers XML_Util::attributesToString() */ public function testAttributesToStringWithExplicitSortFalse() { $original = array('foo' => 'bar','boo' => 'baz',); $expected = " foo=\"bar\" boo=\"baz\""; $sort = false; $this->assertEquals($expected, XML_Util::attributesToString($original, $sort)); } /** * @covers XML_Util::attributesToString() */ public function testAttributesToStringWithMultilineFalse() { $original = array('foo' => 'bar','boo' => 'baz',); $expected = " boo=\"baz\" foo=\"bar\""; $sort = true; $multiline = false; $this->assertEquals($expected, XML_Util::attributesToString($original, $sort, $multiline)); } /** * @covers XML_Util::attributesToString() */ public function testAttributesToStringWithMultilineTrue() { $original = array('foo' => 'bar','boo' => 'baz',); $expected = <<< EOF boo="baz" foo="bar" EOF; $sort = true; $multiline = true; $this->assertEquals($expected, XML_Util::attributesToString($original, $sort, $multiline)); } /** * @covers XML_Util::attributesToString() */ public function testAttributesToStringWithExplicitIndent() { $original = array('foo' => 'bar','boo' => 'baz',); $expected = " boo=\"baz\"\n foo=\"bar\""; $sort = true; $multiline = true; $indent = ' '; // 8 spaces $this->assertEquals($expected, XML_Util::attributesToString($original, $sort, $multiline, $indent)); } /** * @covers XML_Util::attributesToString() */ public function testAttributesToStringWithExplicitLinebreak() { $original = array('foo' => 'bar','boo' => 'baz',); $expected = " boo=\"baz\"\n^foo=\"bar\""; $sort = true; $multiline = true; $linebreak = '^'; // some dummy character $this->assertEquals($expected, XML_Util::attributesToString($original, $sort, $multiline, $linebreak)); } /** * @covers XML_Util::attributesToString() */ public function testAttributesToStringWithOptionsThatIncludesSort() { $original = array('foo' => 'bar','boo' => 'baz',); $options = array( 'multiline' => true, 'indent' => '----', 'linebreak' => "^", 'entities' => XML_UTIL_ENTITIES_XML, 'sort' => true, ); $expected = " boo=\"baz\"\n----foo=\"bar\""; $this->assertEquals($expected, XML_Util::attributesToString($original, $options)); } /** * @covers XML_Util::attributesToString() */ public function testAttributesToStringWithOptionsThatExcludesSort() { $original = array('foo' => 'bar','boo' => 'baz',); $options = array( 'multiline' => true, 'indent' => '----', 'linebreak' => "^", 'entities' => XML_UTIL_ENTITIES_XML, ); $expected = " boo=\"baz\"\n----foo=\"bar\""; $this->assertEquals($expected, XML_Util::attributesToString($original, $options)); } /** * @covers XML_Util::attributesToString() */ public function testAttributesToStringWithEntitiesNone() { $original = array("foo" => "b@&r", "boo" => "b>assertEquals($expected, XML_Util::attributesToString($original, $sort, $multiline, $linebreak, PHP_EOL, XML_UTIL_ENTITIES_NONE)); } /** * @covers XML_Util::attributesToString() */ public function testAttributesToStringWithEntitiesXml() { $original = array("foo" => "b@&r", "boo" => "b>assertEquals($expected, XML_Util::attributesToString($original, $sort, $multiline, $linebreak, PHP_EOL, XML_UTIL_ENTITIES_XML)); } /** * @covers XML_Util::attributesToString() */ public function testAttributesToStringWithEntitiesXmlRequired() { $original = array("foo" => "b@&r", "boo" => "b><z\" foo=\"b@&r\""; $sort = true; $multiline = false; $linebreak = ' '; $this->assertEquals($expected, XML_Util::attributesToString($original, $sort, $multiline, $linebreak, PHP_EOL, XML_UTIL_ENTITIES_XML_REQUIRED)); } /** * @covers XML_Util::attributesToString() */ public function testAttributesToStringWithEntitiesHtml() { $original = array("foo" => "b@&r", "boo" => "b>assertEquals($expected, XML_Util::attributesToString($original, $sort, $multiline, $linebreak, PHP_EOL, XML_UTIL_ENTITIES_HTML)); } /** * Tag attributes should not be treated as CDATA, * so the operation will instead quietly use XML_UTIL_ENTITIES_XML. * * @covers XML_Util::attributesToString() */ public function testAttributesToStringWithCDataSectionForSingleAttribute() { $original = array('foo' => 'bar'); // need exactly one attribute here $options = array( 'sort' => true, // doesn't matter for this testcase 'multiline' => false, // doesn't matter for this testcase 'indent' => null, // doesn't matter for this testcase 'linebreak' => null, // doesn't matter for this testcase 'entities' => XML_UTIL_CDATA_SECTION, // DOES matter for this testcase ); $expected = " foo=\"bar\""; $this->assertEquals($expected, XML_Util::attributesToString($original, $options)); } /** * Tag attributes should not be treated as CDATA, * so the operation will instead quietly use XML_UTIL_ENTITIES_XML. * * @covers XML_Util::attributesToString() */ public function testAttributesToStringWithCDataSectionForMultipleAttributesAndMultilineFalse() { $original = array('foo' => 'bar', 'boo' => 'baz'); // need more than one attribute here $options = array( 'sort' => true, // doesn't matter for this testcase 'multiline' => false, // DOES matter for this testcase, must be false 'indent' => null, // doesn't matter for this testcase 'linebreak' => null, // doesn't matter for this testcase 'entities' => XML_UTIL_CDATA_SECTION, // DOES matter for this testcase ); $expected = " boo=\"baz\" foo=\"bar\""; $this->assertEquals($expected, XML_Util::attributesToString($original, $options)); } } PK!ݑh(pear/XML_Util/tests/IsValidNameTests.phpnu[assertTrue($result); } /** * @covers XML_Util::isValidName() */ public function testIsValidNameForTagNameWithInvalidCharacter() { $tagName = "invalidTag?"; $result = XML_Util::isValidName($tagName); $this->assertInstanceOf('PEAR_Error', $result); $expectedError = "XML names may only contain alphanumeric chars, period, hyphen, colon and underscores"; $this->assertEquals($expectedError, $result->getMessage()); } /** * @covers XML_Util::isValidName() */ public function testIsValidNameForTagNameWithInvalidStartingCharacter() { $tagName = "1234five"; $result = XML_Util::isValidName($tagName); $this->assertInstanceOf('PEAR_Error', $result); $expectedError = "XML names may only start with letter or underscore"; $this->assertEquals($expectedError, $result->getMessage()); } /** * @covers XML_Util::isValidName() */ public function testIsValidNameForInt() { $tagName = 1; $result = XML_Util::isValidName($tagName); $this->assertInstanceOf('PEAR_Error', $result); $expectedError = "XML names may only start with letter or underscore"; $this->assertEquals($expectedError, $result->getMessage()); } /** * @covers XML_Util::isValidName() */ public function testIsValidNameForEmptyString() { $tagName = ''; $result = XML_Util::isValidName($tagName); $this->assertInstanceOf('PEAR_Error', $result); $expectedError = "XML names may only start with letter or underscore"; $this->assertEquals($expectedError, $result->getMessage()); } } PK!TT*pear/XML_Util/tests/CreateCommentTests.phpnu["; $this->assertEquals($expected, XML_Util::createComment($original)); } } PK!rv'pear/XML_Util/tests/RaiseErrorTests.phpnu[assertInstanceOf('PEAR_Error', $error); $this->assertEquals($message, $error->getMessage()); $this->assertEquals($code, $error->getCode()); } } PK! __init__.pynu[# -*- coding: utf-8 -*- # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Test utilities. """ from __future__ import print_function import atexit import contextlib import ctypes import errno import functools import os import random import re import select import shutil import socket import stat import subprocess import sys import tempfile import textwrap import threading import time import traceback import warnings from socket import AF_INET from socket import AF_INET6 from socket import SOCK_DGRAM from socket import SOCK_STREAM import psutil from psutil import OSX from psutil import POSIX from psutil import SUNOS from psutil import WINDOWS from psutil._common import supports_ipv6 from psutil._compat import PY3 from psutil._compat import u from psutil._compat import unicode from psutil._compat import which if sys.version_info < (2, 7): import unittest2 as unittest # requires "pip install unittest2" else: import unittest try: from unittest import mock # py3 except ImportError: import mock # NOQA - requires "pip install mock" if sys.version_info >= (3, 4): import enum else: enum = None __all__ = [ # constants 'APPVEYOR', 'DEVNULL', 'GLOBAL_TIMEOUT', 'MEMORY_TOLERANCE', 'NO_RETRIES', 'PYPY', 'PYTHON_EXE', 'ROOT_DIR', 'SCRIPTS_DIR', 'TESTFILE_PREFIX', 'TESTFN', 'TESTFN_UNICODE', 'TOX', 'TRAVIS', 'VALID_PROC_STATUSES', 'VERBOSITY', "HAS_CPU_AFFINITY", "HAS_CPU_FREQ", "HAS_ENVIRON", "HAS_PROC_IO_COUNTERS", "HAS_IONICE", "HAS_MEMORY_MAPS", "HAS_PROC_CPU_NUM", "HAS_RLIMIT", "HAS_SENSORS_BATTERY", "HAS_BATTERY", "HAS_SENSORS_FANS", "HAS_SENSORS_TEMPERATURES", "HAS_MEMORY_FULL_INFO", # subprocesses 'pyrun', 'reap_children', 'get_test_subprocess', 'create_zombie_proc', 'create_proc_children_pair', # threads 'ThreadTask' # test utils 'unittest', 'skip_on_access_denied', 'skip_on_not_implemented', 'retry_before_failing', 'run_test_module_by_name', 'get_suite', 'run_suite', # install utils 'install_pip', 'install_test_deps', # fs utils 'chdir', 'safe_rmpath', 'create_exe', 'decode_path', 'encode_path', 'unique_filename', # os 'get_winver', 'get_kernel_version', # sync primitives 'call_until', 'wait_for_pid', 'wait_for_file', # network 'check_connection_ntuple', 'check_net_address', 'get_free_port', 'unix_socket_path', 'bind_socket', 'bind_unix_socket', 'tcp_socketpair', 'unix_socketpair', 'create_sockets', # compat 'reload_module', 'import_module_by_path', # others 'warn', 'copyload_shared_lib', 'is_namedtuple', ] # =================================================================== # --- constants # =================================================================== # --- platforms TOX = os.getenv('TOX') or '' in ('1', 'true') PYPY = '__pypy__' in sys.builtin_module_names WIN_VISTA = (6, 0, 0) if WINDOWS else None # whether we're running this test suite on Travis (https://travis-ci.org/) TRAVIS = bool(os.environ.get('TRAVIS')) # whether we're running this test suite on Appveyor for Windows # (http://www.appveyor.com/) APPVEYOR = bool(os.environ.get('APPVEYOR')) # --- configurable defaults # how many times retry_before_failing() decorator will retry NO_RETRIES = 10 # bytes tolerance for system-wide memory related tests MEMORY_TOLERANCE = 500 * 1024 # 500KB # the timeout used in functions which have to wait GLOBAL_TIMEOUT = 3 # test output verbosity VERBOSITY = 1 if os.getenv('SILENT') or TOX else 2 # be more tolerant if we're on travis / appveyor in order to avoid # false positives if TRAVIS or APPVEYOR: NO_RETRIES *= 3 GLOBAL_TIMEOUT *= 3 # --- files TESTFILE_PREFIX = '$testfn' TESTFN = os.path.join(os.path.realpath(os.getcwd()), TESTFILE_PREFIX) _TESTFN = TESTFN + '-internal' TESTFN_UNICODE = TESTFN + u("-ƒőő") ASCII_FS = sys.getfilesystemencoding().lower() in ('ascii', 'us-ascii') # --- paths ROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')) SCRIPTS_DIR = os.path.join(ROOT_DIR, 'scripts') HERE = os.path.abspath(os.path.dirname(__file__)) # --- support HAS_CPU_AFFINITY = hasattr(psutil.Process, "cpu_affinity") HAS_CPU_FREQ = hasattr(psutil, "cpu_freq") HAS_CONNECTIONS_UNIX = POSIX and not SUNOS HAS_ENVIRON = hasattr(psutil.Process, "environ") HAS_PROC_IO_COUNTERS = hasattr(psutil.Process, "io_counters") HAS_IONICE = hasattr(psutil.Process, "ionice") HAS_MEMORY_FULL_INFO = 'uss' in psutil.Process().memory_full_info()._fields HAS_MEMORY_MAPS = hasattr(psutil.Process, "memory_maps") HAS_PROC_CPU_NUM = hasattr(psutil.Process, "cpu_num") HAS_RLIMIT = hasattr(psutil.Process, "rlimit") HAS_THREADS = hasattr(psutil.Process, "threads") HAS_SENSORS_BATTERY = hasattr(psutil, "sensors_battery") HAS_BATTERY = HAS_SENSORS_BATTERY and psutil.sensors_battery() HAS_SENSORS_FANS = hasattr(psutil, "sensors_fans") HAS_SENSORS_TEMPERATURES = hasattr(psutil, "sensors_temperatures") # --- misc def _get_py_exe(): def attempt(exe): try: subprocess.check_call( [exe, "-V"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) except Exception: return None else: return exe if OSX: exe = \ attempt(sys.executable) or \ attempt(os.path.realpath(sys.executable)) or \ attempt(which("python%s.%s" % sys.version_info[:2])) or \ attempt(psutil.Process().exe()) if not exe: raise ValueError("can't find python exe real abspath") return exe else: exe = os.path.realpath(sys.executable) assert os.path.exists(exe), exe return exe PYTHON_EXE = _get_py_exe() DEVNULL = open(os.devnull, 'r+') VALID_PROC_STATUSES = [getattr(psutil, x) for x in dir(psutil) if x.startswith('STATUS_')] AF_UNIX = getattr(socket, "AF_UNIX", object()) SOCK_SEQPACKET = getattr(socket, "SOCK_SEQPACKET", object()) _subprocesses_started = set() _pids_started = set() _testfiles_created = set() @atexit.register def _cleanup_files(): DEVNULL.close() for name in os.listdir(u('.')): if isinstance(name, unicode): prefix = u(TESTFILE_PREFIX) else: prefix = TESTFILE_PREFIX if name.startswith(prefix): try: safe_rmpath(name) except Exception: traceback.print_exc() for path in _testfiles_created: try: safe_rmpath(path) except Exception: traceback.print_exc() # this is executed first @atexit.register def _cleanup_procs(): reap_children(recursive=True) # =================================================================== # --- threads # =================================================================== class ThreadTask(threading.Thread): """A thread task which does nothing expect staying alive.""" def __init__(self): threading.Thread.__init__(self) self._running = False self._interval = 0.001 self._flag = threading.Event() def __repr__(self): name = self.__class__.__name__ return '<%s running=%s at %#x>' % (name, self._running, id(self)) def __enter__(self): self.start() return self def __exit__(self, *args, **kwargs): self.stop() def start(self): """Start thread and keep it running until an explicit stop() request. Polls for shutdown every 'timeout' seconds. """ if self._running: raise ValueError("already started") threading.Thread.start(self) self._flag.wait() def run(self): self._running = True self._flag.set() while self._running: time.sleep(self._interval) def stop(self): """Stop thread execution and and waits until it is stopped.""" if not self._running: raise ValueError("already stopped") self._running = False self.join() # =================================================================== # --- subprocesses # =================================================================== def _cleanup_on_err(fun): @functools.wraps(fun) def wrapper(*args, **kwargs): try: return fun(*args, **kwargs) except Exception: reap_children() raise return wrapper @_cleanup_on_err def get_test_subprocess(cmd=None, **kwds): """Creates a python subprocess which does nothing for 60 secs and return it as subprocess.Popen instance. If "cmd" is specified that is used instead of python. By default stdin and stdout are redirected to /dev/null. It also attemps to make sure the process is in a reasonably initialized state. The process is registered for cleanup on reap_children(). """ kwds.setdefault("stdin", DEVNULL) kwds.setdefault("stdout", DEVNULL) kwds.setdefault("cwd", os.getcwd()) kwds.setdefault("env", os.environ) if WINDOWS: # Prevents the subprocess to open error dialogs. kwds.setdefault("creationflags", 0x8000000) # CREATE_NO_WINDOW if cmd is None: safe_rmpath(_TESTFN) pyline = "from time import sleep;" \ "open(r'%s', 'w').close();" \ "sleep(60);" % _TESTFN cmd = [PYTHON_EXE, "-c", pyline] sproc = subprocess.Popen(cmd, **kwds) _subprocesses_started.add(sproc) wait_for_file(_TESTFN, delete=True, empty=True) else: sproc = subprocess.Popen(cmd, **kwds) _subprocesses_started.add(sproc) wait_for_pid(sproc.pid) return sproc @_cleanup_on_err def create_proc_children_pair(): """Create a subprocess which creates another one as in: A (us) -> B (child) -> C (grandchild). Return a (child, grandchild) tuple. The 2 processes are fully initialized and will live for 60 secs and are registered for cleanup on reap_children(). """ _TESTFN2 = os.path.basename(_TESTFN) + '2' # need to be relative s = textwrap.dedent("""\ import subprocess, os, sys, time s = "import os, time;" s += "f = open('%s', 'w');" s += "f.write(str(os.getpid()));" s += "f.close();" s += "time.sleep(60);" subprocess.Popen(['%s', '-c', s]) time.sleep(60) """ % (_TESTFN2, PYTHON_EXE)) # On Windows if we create a subprocess with CREATE_NO_WINDOW flag # set (which is the default) a "conhost.exe" extra process will be # spawned as a child. We don't want that. if WINDOWS: subp = pyrun(s, creationflags=0) else: subp = pyrun(s) child1 = psutil.Process(subp.pid) data = wait_for_file(_TESTFN2, delete=False, empty=False) os.remove(_TESTFN2) child2_pid = int(data) _pids_started.add(child2_pid) child2 = psutil.Process(child2_pid) return (child1, child2) def create_zombie_proc(): """Create a zombie process and return its PID.""" assert psutil.POSIX unix_file = tempfile.mktemp(prefix=TESTFILE_PREFIX) if OSX else TESTFN src = textwrap.dedent("""\ import os, sys, time, socket, contextlib child_pid = os.fork() if child_pid > 0: time.sleep(3000) else: # this is the zombie process s = socket.socket(socket.AF_UNIX) with contextlib.closing(s): s.connect('%s') if sys.version_info < (3, ): pid = str(os.getpid()) else: pid = bytes(str(os.getpid()), 'ascii') s.sendall(pid) """ % unix_file) with contextlib.closing(socket.socket(socket.AF_UNIX)) as sock: sock.settimeout(GLOBAL_TIMEOUT) sock.bind(unix_file) sock.listen(1) pyrun(src) conn, _ = sock.accept() try: select.select([conn.fileno()], [], [], GLOBAL_TIMEOUT) zpid = int(conn.recv(1024)) _pids_started.add(zpid) zproc = psutil.Process(zpid) call_until(lambda: zproc.status(), "ret == psutil.STATUS_ZOMBIE") return zpid finally: conn.close() @_cleanup_on_err def pyrun(src, **kwds): """Run python 'src' code string in a separate interpreter. Returns a subprocess.Popen instance. """ kwds.setdefault("stdout", None) kwds.setdefault("stderr", None) with tempfile.NamedTemporaryFile( prefix=TESTFILE_PREFIX, mode="wt", delete=False) as f: _testfiles_created.add(f.name) f.write(src) f.flush() subp = get_test_subprocess([PYTHON_EXE, f.name], **kwds) wait_for_pid(subp.pid) return subp @_cleanup_on_err def sh(cmd, **kwds): """run cmd in a subprocess and return its output. raises RuntimeError on error. """ shell = True if isinstance(cmd, (str, unicode)) else False # Prevents subprocess to open error dialogs in case of error. flags = 0x8000000 if WINDOWS and shell else 0 kwds.setdefault("shell", shell) kwds.setdefault("stdout", subprocess.PIPE) kwds.setdefault("stderr", subprocess.PIPE) kwds.setdefault("universal_newlines", True) kwds.setdefault("creationflags", flags) p = subprocess.Popen(cmd, **kwds) _subprocesses_started.add(p) stdout, stderr = p.communicate() if p.returncode != 0: raise RuntimeError(stderr) if stderr: warn(stderr) if stdout.endswith('\n'): stdout = stdout[:-1] return stdout def reap_children(recursive=False): """Terminate and wait() any subprocess started by this test suite and ensure that no zombies stick around to hog resources and create problems when looking for refleaks. If resursive is True it also tries to terminate and wait() all grandchildren started by this process. """ # This is here to make sure wait_procs() behaves properly and # investigate: # https://ci.appveyor.com/project/giampaolo/psutil/build/job/ # jiq2cgd6stsbtn60 def assert_gone(pid): assert not psutil.pid_exists(pid), pid assert pid not in psutil.pids(), pid try: p = psutil.Process(pid) assert not p.is_running(), pid except psutil.NoSuchProcess: pass else: assert 0, "pid %s is not gone" % pid # Get the children here, before terminating the children sub # processes as we don't want to lose the intermediate reference # in case of grandchildren. if recursive: children = set(psutil.Process().children(recursive=True)) else: children = set() # Terminate subprocess.Popen instances "cleanly" by closing their # fds and wiat()ing for them in order to avoid zombies. while _subprocesses_started: subp = _subprocesses_started.pop() _pids_started.add(subp.pid) try: subp.terminate() except OSError as err: if err.errno != errno.ESRCH: raise if subp.stdout: subp.stdout.close() if subp.stderr: subp.stderr.close() try: # Flushing a BufferedWriter may raise an error. if subp.stdin: subp.stdin.close() finally: # Wait for the process to terminate, to avoid zombies. try: subp.wait() except OSError as err: if err.errno != errno.ECHILD: raise # Terminate started pids. while _pids_started: pid = _pids_started.pop() try: p = psutil.Process(pid) except psutil.NoSuchProcess: assert_gone(pid) else: children.add(p) # Terminate children. if children: for p in children: try: p.terminate() except psutil.NoSuchProcess: pass gone, alive = psutil.wait_procs(children, timeout=GLOBAL_TIMEOUT) for p in alive: warn("couldn't terminate process %r; attempting kill()" % p) try: p.kill() except psutil.NoSuchProcess: pass gone, alive = psutil.wait_procs(alive, timeout=GLOBAL_TIMEOUT) if alive: for p in alive: warn("process %r survived kill()" % p) for p in children: assert_gone(p.pid) # =================================================================== # --- OS # =================================================================== def get_kernel_version(): """Return a tuple such as (2, 6, 36).""" if not POSIX: raise NotImplementedError("not POSIX") s = "" uname = os.uname()[2] for c in uname: if c.isdigit() or c == '.': s += c else: break if not s: raise ValueError("can't parse %r" % uname) minor = 0 micro = 0 nums = s.split('.') major = int(nums[0]) if len(nums) >= 2: minor = int(nums[1]) if len(nums) >= 3: micro = int(nums[2]) return (major, minor, micro) def get_winver(): if not WINDOWS: raise NotImplementedError("not WINDOWS") wv = sys.getwindowsversion() if hasattr(wv, 'service_pack_major'): # python >= 2.7 sp = wv.service_pack_major or 0 else: r = re.search(r"\s\d$", wv[4]) if r: sp = int(r.group(0)) else: sp = 0 return (wv[0], wv[1], sp) # =================================================================== # --- sync primitives # =================================================================== class retry(object): """A retry decorator.""" def __init__(self, exception=Exception, timeout=None, retries=None, interval=0.001, logfun=lambda s: print(s, file=sys.stderr), ): if timeout and retries: raise ValueError("timeout and retries args are mutually exclusive") self.exception = exception self.timeout = timeout self.retries = retries self.interval = interval self.logfun = logfun def __iter__(self): if self.timeout: stop_at = time.time() + self.timeout while time.time() < stop_at: yield elif self.retries: for _ in range(self.retries): yield else: while True: yield def sleep(self): if self.interval is not None: time.sleep(self.interval) def __call__(self, fun): @functools.wraps(fun) def wrapper(*args, **kwargs): exc = None for _ in self: try: return fun(*args, **kwargs) except self.exception as _: exc = _ if self.logfun is not None: self.logfun(exc) self.sleep() continue if PY3: raise exc else: raise # This way the user of the decorated function can change config # parameters. wrapper.decorator = self return wrapper @retry(exception=psutil.NoSuchProcess, logfun=None, timeout=GLOBAL_TIMEOUT, interval=0.001) def wait_for_pid(pid): """Wait for pid to show up in the process list then return. Used in the test suite to give time the sub process to initialize. """ psutil.Process(pid) if WINDOWS: # give it some more time to allow better initialization time.sleep(0.01) @retry(exception=(EnvironmentError, AssertionError), logfun=None, timeout=GLOBAL_TIMEOUT, interval=0.001) def wait_for_file(fname, delete=True, empty=False): """Wait for a file to be written on disk with some content.""" with open(fname, "rb") as f: data = f.read() if not empty: assert data if delete: os.remove(fname) return data @retry(exception=AssertionError, logfun=None, timeout=GLOBAL_TIMEOUT, interval=0.001) def call_until(fun, expr): """Keep calling function for timeout secs and exit if eval() expression is True. """ ret = fun() assert eval(expr) return ret # =================================================================== # --- fs # =================================================================== def safe_rmpath(path): "Convenience function for removing temporary test files or dirs" try: st = os.stat(path) if stat.S_ISDIR(st.st_mode): os.rmdir(path) else: os.remove(path) except OSError as err: if err.errno != errno.ENOENT: raise def safe_mkdir(dir): "Convenience function for creating a directory" try: os.mkdir(dir) except OSError as err: if err.errno != errno.EEXIST: raise @contextlib.contextmanager def chdir(dirname): "Context manager which temporarily changes the current directory." curdir = os.getcwd() try: os.chdir(dirname) yield finally: os.chdir(curdir) def create_exe(outpath, c_code=None): """Creates an executable file in the given location.""" assert not os.path.exists(outpath), outpath if c_code: if not which("gcc"): raise ValueError("gcc is not installed") if isinstance(c_code, bool): # c_code is True c_code = textwrap.dedent( """ #include int main() { pause(); return 1; } """) assert isinstance(c_code, str), c_code with tempfile.NamedTemporaryFile( suffix='.c', delete=False, mode='wt') as f: f.write(c_code) try: subprocess.check_call(["gcc", f.name, "-o", outpath]) finally: safe_rmpath(f.name) else: # copy python executable shutil.copyfile(PYTHON_EXE, outpath) if POSIX: st = os.stat(outpath) os.chmod(outpath, st.st_mode | stat.S_IEXEC) def unique_filename(prefix=TESTFILE_PREFIX, suffix=""): return tempfile.mktemp(prefix=prefix, suffix=suffix) # =================================================================== # --- testing # =================================================================== class TestCase(unittest.TestCase): # Print a full path representation of the single unit tests # being run. def __str__(self): return "%s.%s.%s" % ( self.__class__.__module__, self.__class__.__name__, self._testMethodName) # assertRaisesRegexp renamed to assertRaisesRegex in 3.3; # add support for the new name. if not hasattr(unittest.TestCase, 'assertRaisesRegex'): assertRaisesRegex = unittest.TestCase.assertRaisesRegexp # override default unittest.TestCase unittest.TestCase = TestCase def _setup_tests(): if 'PSUTIL_TESTING' not in os.environ: # This won't work on Windows but set_testing() below will do it. os.environ['PSUTIL_TESTING'] = '1' psutil._psplatform.cext.set_testing() def get_suite(): testmods = [os.path.splitext(x)[0] for x in os.listdir(HERE) if x.endswith('.py') and x.startswith('test_') and not x.startswith('test_memory_leaks')] if "WHEELHOUSE_UPLOADER_USERNAME" in os.environ: testmods = [x for x in testmods if not x.endswith(( "osx", "posix", "linux"))] suite = unittest.TestSuite() for tm in testmods: # ...so that the full test paths are printed on screen tm = "psutil.tests.%s" % tm suite.addTest(unittest.defaultTestLoader.loadTestsFromName(tm)) return suite def run_suite(): _setup_tests() result = unittest.TextTestRunner(verbosity=VERBOSITY).run(get_suite()) success = result.wasSuccessful() sys.exit(0 if success else 1) def run_test_module_by_name(name): # testmodules = [os.path.splitext(x)[0] for x in os.listdir(HERE) # if x.endswith('.py') and x.startswith('test_')] _setup_tests() name = os.path.splitext(os.path.basename(name))[0] suite = unittest.TestSuite() suite.addTest(unittest.defaultTestLoader.loadTestsFromName(name)) result = unittest.TextTestRunner(verbosity=VERBOSITY).run(suite) success = result.wasSuccessful() sys.exit(0 if success else 1) def retry_before_failing(retries=NO_RETRIES): """Decorator which runs a test function and retries N times before actually failing. """ return retry(exception=AssertionError, timeout=None, retries=retries) def skip_on_access_denied(only_if=None): """Decorator to Ignore AccessDenied exceptions.""" def decorator(fun): @functools.wraps(fun) def wrapper(*args, **kwargs): try: return fun(*args, **kwargs) except psutil.AccessDenied: if only_if is not None: if not only_if: raise raise unittest.SkipTest("raises AccessDenied") return wrapper return decorator def skip_on_not_implemented(only_if=None): """Decorator to Ignore NotImplementedError exceptions.""" def decorator(fun): @functools.wraps(fun) def wrapper(*args, **kwargs): try: return fun(*args, **kwargs) except NotImplementedError: if only_if is not None: if not only_if: raise msg = "%r was skipped because it raised NotImplementedError" \ % fun.__name__ raise unittest.SkipTest(msg) return wrapper return decorator # =================================================================== # --- network # =================================================================== def get_free_port(host='127.0.0.1'): """Return an unused TCP port.""" with contextlib.closing(socket.socket()) as sock: sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind((host, 0)) return sock.getsockname()[1] @contextlib.contextmanager def unix_socket_path(suffix=""): """A context manager which returns a non-existent file name and tries to delete it on exit. """ assert psutil.POSIX path = unique_filename(suffix=suffix) try: yield path finally: try: os.unlink(path) except OSError: pass def bind_socket(family=AF_INET, type=SOCK_STREAM, addr=None): """Binds a generic socket.""" if addr is None and family in (AF_INET, AF_INET6): addr = ("", 0) sock = socket.socket(family, type) try: sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(addr) if type == socket.SOCK_STREAM: sock.listen(10) return sock except Exception: sock.close() raise def bind_unix_socket(name, type=socket.SOCK_STREAM): """Bind a UNIX socket.""" assert psutil.POSIX assert not os.path.exists(name), name sock = socket.socket(socket.AF_UNIX, type) try: sock.bind(name) if type == socket.SOCK_STREAM: sock.listen(10) except Exception: sock.close() raise return sock def tcp_socketpair(family, addr=("", 0)): """Build a pair of TCP sockets connected to each other. Return a (server, client) tuple. """ with contextlib.closing(socket.socket(family, SOCK_STREAM)) as ll: ll.bind(addr) ll.listen(10) addr = ll.getsockname() c = socket.socket(family, SOCK_STREAM) try: c.connect(addr) caddr = c.getsockname() while True: a, addr = ll.accept() # check that we've got the correct client if addr == caddr: return (a, c) a.close() except OSError: c.close() raise def unix_socketpair(name): """Build a pair of UNIX sockets connected to each other through the same UNIX file name. Return a (server, client) tuple. """ assert psutil.POSIX server = client = None try: server = bind_unix_socket(name, type=socket.SOCK_STREAM) server.setblocking(0) client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) client.setblocking(0) client.connect(name) # new = server.accept() except Exception: if server is not None: server.close() if client is not None: client.close() raise return (server, client) @contextlib.contextmanager def create_sockets(): """Open as many socket families / types as possible.""" socks = [] fname1 = fname2 = None try: socks.append(bind_socket(socket.AF_INET, socket.SOCK_STREAM)) socks.append(bind_socket(socket.AF_INET, socket.SOCK_DGRAM)) if supports_ipv6(): socks.append(bind_socket(socket.AF_INET6, socket.SOCK_STREAM)) socks.append(bind_socket(socket.AF_INET6, socket.SOCK_DGRAM)) if POSIX and HAS_CONNECTIONS_UNIX: fname1 = unix_socket_path().__enter__() fname2 = unix_socket_path().__enter__() s1, s2 = unix_socketpair(fname1) s3 = bind_unix_socket(fname2, type=socket.SOCK_DGRAM) # self.addCleanup(safe_rmpath, fname1) # self.addCleanup(safe_rmpath, fname2) for s in (s1, s2, s3): socks.append(s) yield socks finally: for s in socks: s.close() if fname1 is not None: safe_rmpath(fname1) if fname2 is not None: safe_rmpath(fname2) def check_net_address(addr, family): """Check a net address validity. Supported families are IPv4, IPv6 and MAC addresses. """ import ipaddress # python >= 3.3 / requires "pip install ipaddress" if enum and PY3: assert isinstance(family, enum.IntEnum), family if family == socket.AF_INET: octs = [int(x) for x in addr.split('.')] assert len(octs) == 4, addr for num in octs: assert 0 <= num <= 255, addr if not PY3: addr = unicode(addr) ipaddress.IPv4Address(addr) elif family == socket.AF_INET6: assert isinstance(addr, str), addr if not PY3: addr = unicode(addr) ipaddress.IPv6Address(addr) elif family == psutil.AF_LINK: assert re.match(r'([a-fA-F0-9]{2}[:|\-]?){6}', addr) is not None, addr else: raise ValueError("unknown family %r", family) def check_connection_ntuple(conn): """Check validity of a connection namedtuple.""" # check ntuple assert len(conn) in (6, 7), conn has_pid = len(conn) == 7 has_fd = getattr(conn, 'fd', -1) != -1 assert conn[0] == conn.fd assert conn[1] == conn.family assert conn[2] == conn.type assert conn[3] == conn.laddr assert conn[4] == conn.raddr assert conn[5] == conn.status if has_pid: assert conn[6] == conn.pid # check fd if has_fd: assert conn.fd >= 0, conn if hasattr(socket, 'fromfd') and not WINDOWS: try: dupsock = socket.fromfd(conn.fd, conn.family, conn.type) except (socket.error, OSError) as err: if err.args[0] != errno.EBADF: raise else: with contextlib.closing(dupsock): assert dupsock.family == conn.family assert dupsock.type == conn.type # check family assert conn.family in (AF_INET, AF_INET6, AF_UNIX), repr(conn.family) if conn.family in (AF_INET, AF_INET6): # actually try to bind the local socket; ignore IPv6 # sockets as their address might be represented as # an IPv4-mapped-address (e.g. "::127.0.0.1") # and that's rejected by bind() if conn.family == AF_INET: s = socket.socket(conn.family, conn.type) with contextlib.closing(s): try: s.bind((conn.laddr[0], 0)) except socket.error as err: if err.errno != errno.EADDRNOTAVAIL: raise elif conn.family == AF_UNIX: assert conn.status == psutil.CONN_NONE, conn.status # check type (SOCK_SEQPACKET may happen in case of AF_UNIX socks) assert conn.type in (SOCK_STREAM, SOCK_DGRAM, SOCK_SEQPACKET), \ repr(conn.type) if conn.type == SOCK_DGRAM: assert conn.status == psutil.CONN_NONE, conn.status # check laddr (IP address and port sanity) for addr in (conn.laddr, conn.raddr): if conn.family in (AF_INET, AF_INET6): assert isinstance(addr, tuple), addr if not addr: continue assert isinstance(addr.port, int), addr.port assert 0 <= addr.port <= 65535, addr.port check_net_address(addr.ip, conn.family) elif conn.family == AF_UNIX: assert isinstance(addr, str), addr # check status assert isinstance(conn.status, str), conn valids = [getattr(psutil, x) for x in dir(psutil) if x.startswith('CONN_')] assert conn.status in valids, conn # =================================================================== # --- compatibility # =================================================================== def reload_module(module): """Backport of importlib.reload of Python 3.3+.""" try: import importlib if not hasattr(importlib, 'reload'): # python <=3.3 raise ImportError except ImportError: import imp return imp.reload(module) else: return importlib.reload(module) def import_module_by_path(path): name = os.path.splitext(os.path.basename(path))[0] if sys.version_info[0] == 2: import imp return imp.load_source(name, path) elif sys.version_info[:2] <= (3, 4): from importlib.machinery import SourceFileLoader return SourceFileLoader(name, path).load_module() else: import importlib.util spec = importlib.util.spec_from_file_location(name, path) mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod) return mod # =================================================================== # --- others # =================================================================== def warn(msg): """Raise a warning msg.""" warnings.warn(msg, UserWarning) def is_namedtuple(x): """Check if object is an instance of namedtuple.""" t = type(x) b = t.__bases__ if len(b) != 1 or b[0] != tuple: return False f = getattr(t, '_fields', None) if not isinstance(f, tuple): return False return all(type(n) == str for n in f) if POSIX: @contextlib.contextmanager def copyload_shared_lib(dst_prefix=TESTFILE_PREFIX): """Ctx manager which picks up a random shared CO lib used by this process, copies it in another location and loads it in memory via ctypes. Return the new absolutized path. """ ext = ".so" dst = tempfile.mktemp(prefix=dst_prefix, suffix=ext) libs = [x.path for x in psutil.Process().memory_maps() if os.path.splitext(x.path)[1] == ext and 'python' in x.path.lower()] src = random.choice(libs) shutil.copyfile(src, dst) try: ctypes.CDLL(dst) yield dst finally: safe_rmpath(dst) else: @contextlib.contextmanager def copyload_shared_lib(dst_prefix=TESTFILE_PREFIX): """Ctx manager which picks up a random shared DLL lib used by this process, copies it in another location and loads it in memory via ctypes. Return the new absolutized, normcased path. """ from ctypes import wintypes from ctypes import WinError ext = ".dll" dst = tempfile.mktemp(prefix=dst_prefix, suffix=ext) libs = [x.path for x in psutil.Process().memory_maps() if os.path.splitext(x.path)[1].lower() == ext and 'python' in os.path.basename(x.path).lower() and 'wow64' not in x.path.lower()] src = random.choice(libs) shutil.copyfile(src, dst) cfile = None try: cfile = ctypes.WinDLL(dst) yield dst finally: # Work around OverflowError: # - https://ci.appveyor.com/project/giampaolo/psutil/build/1207/ # job/o53330pbnri9bcw7 # - http://bugs.python.org/issue30286 # - http://stackoverflow.com/questions/23522055 if cfile is not None: FreeLibrary = ctypes.windll.kernel32.FreeLibrary FreeLibrary.argtypes = [wintypes.HMODULE] ret = FreeLibrary(cfile._handle) if ret == 0: WinError() safe_rmpath(dst) PK!wӷKKtest_windows.pynu[# -*- coding: UTF-8 -* # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Windows specific tests.""" import datetime import errno import glob import os import platform import re import signal import subprocess import sys import time import warnings import psutil from psutil import WINDOWS from psutil._compat import callable from psutil.tests import APPVEYOR from psutil.tests import get_test_subprocess from psutil.tests import HAS_BATTERY from psutil.tests import mock from psutil.tests import reap_children from psutil.tests import retry_before_failing from psutil.tests import run_test_module_by_name from psutil.tests import sh from psutil.tests import unittest with warnings.catch_warnings(): warnings.simplefilter("ignore") try: import win32api # requires "pip install pypiwin32" import win32con import win32process import wmi # requires "pip install wmi" / "make setup-dev-env" except ImportError: if os.name == 'nt': raise cext = psutil._psplatform.cext # are we a 64 bit process IS_64_BIT = sys.maxsize > 2**32 def wrap_exceptions(fun): def wrapper(self, *args, **kwargs): try: return fun(self, *args, **kwargs) except OSError as err: from psutil._pswindows import ACCESS_DENIED_SET if err.errno in ACCESS_DENIED_SET: raise psutil.AccessDenied(None, None) if err.errno == errno.ESRCH: raise psutil.NoSuchProcess(None, None) raise return wrapper # =================================================================== # System APIs # =================================================================== @unittest.skipIf(not WINDOWS, "WINDOWS only") class TestSystemAPIs(unittest.TestCase): def test_nic_names(self): out = sh('ipconfig /all') nics = psutil.net_io_counters(pernic=True).keys() for nic in nics: if "pseudo-interface" in nic.replace(' ', '-').lower(): continue if nic not in out: self.fail( "%r nic wasn't found in 'ipconfig /all' output" % nic) @unittest.skipIf('NUMBER_OF_PROCESSORS' not in os.environ, 'NUMBER_OF_PROCESSORS env var is not available') def test_cpu_count(self): num_cpus = int(os.environ['NUMBER_OF_PROCESSORS']) self.assertEqual(num_cpus, psutil.cpu_count()) def test_cpu_count_2(self): sys_value = win32api.GetSystemInfo()[5] psutil_value = psutil.cpu_count() self.assertEqual(sys_value, psutil_value) def test_cpu_freq(self): w = wmi.WMI() proc = w.Win32_Processor()[0] self.assertEqual(proc.CurrentClockSpeed, psutil.cpu_freq().current) self.assertEqual(proc.MaxClockSpeed, psutil.cpu_freq().max) def test_total_phymem(self): w = wmi.WMI().Win32_ComputerSystem()[0] self.assertEqual(int(w.TotalPhysicalMemory), psutil.virtual_memory().total) # @unittest.skipIf(wmi is None, "wmi module is not installed") # def test__UPTIME(self): # # _UPTIME constant is not public but it is used internally # # as value to return for pid 0 creation time. # # WMI behaves the same. # w = wmi.WMI().Win32_Process(ProcessId=self.pid)[0] # p = psutil.Process(0) # wmic_create = str(w.CreationDate.split('.')[0]) # psutil_create = time.strftime("%Y%m%d%H%M%S", # time.localtime(p.create_time())) # Note: this test is not very reliable @unittest.skipIf(APPVEYOR, "test not relieable on appveyor") @retry_before_failing() def test_pids(self): # Note: this test might fail if the OS is starting/killing # other processes in the meantime w = wmi.WMI().Win32_Process() wmi_pids = set([x.ProcessId for x in w]) psutil_pids = set(psutil.pids()) self.assertEqual(wmi_pids, psutil_pids) @retry_before_failing() def test_disks(self): ps_parts = psutil.disk_partitions(all=True) wmi_parts = wmi.WMI().Win32_LogicalDisk() for ps_part in ps_parts: for wmi_part in wmi_parts: if ps_part.device.replace('\\', '') == wmi_part.DeviceID: if not ps_part.mountpoint: # this is usually a CD-ROM with no disk inserted break try: usage = psutil.disk_usage(ps_part.mountpoint) except OSError as err: if err.errno == errno.ENOENT: # usually this is the floppy break else: raise self.assertEqual(usage.total, int(wmi_part.Size)) wmi_free = int(wmi_part.FreeSpace) self.assertEqual(usage.free, wmi_free) # 10 MB tollerance if abs(usage.free - wmi_free) > 10 * 1024 * 1024: self.fail("psutil=%s, wmi=%s" % ( usage.free, wmi_free)) break else: self.fail("can't find partition %s" % repr(ps_part)) def test_disk_usage(self): for disk in psutil.disk_partitions(): sys_value = win32api.GetDiskFreeSpaceEx(disk.mountpoint) psutil_value = psutil.disk_usage(disk.mountpoint) self.assertAlmostEqual(sys_value[0], psutil_value.free, delta=1024 * 1024) self.assertAlmostEqual(sys_value[1], psutil_value.total, delta=1024 * 1024) self.assertEqual(psutil_value.used, psutil_value.total - psutil_value.free) def test_disk_partitions(self): sys_value = [ x + '\\' for x in win32api.GetLogicalDriveStrings().split("\\\x00") if x and not x.startswith('A:')] psutil_value = [x.mountpoint for x in psutil.disk_partitions(all=True)] self.assertEqual(sys_value, psutil_value) def test_net_if_stats(self): ps_names = set(cext.net_if_stats()) wmi_adapters = wmi.WMI().Win32_NetworkAdapter() wmi_names = set() for wmi_adapter in wmi_adapters: wmi_names.add(wmi_adapter.Name) wmi_names.add(wmi_adapter.NetConnectionID) self.assertTrue(ps_names & wmi_names, "no common entries in %s, %s" % (ps_names, wmi_names)) def test_boot_time(self): wmi_os = wmi.WMI().Win32_OperatingSystem() wmi_btime_str = wmi_os[0].LastBootUpTime.split('.')[0] wmi_btime_dt = datetime.datetime.strptime( wmi_btime_str, "%Y%m%d%H%M%S") psutil_dt = datetime.datetime.fromtimestamp(psutil.boot_time()) diff = abs((wmi_btime_dt - psutil_dt).total_seconds()) # Wmic time is 2-3 secs lower for some reason; that's OK. self.assertLessEqual(diff, 3) def test_boot_time_fluctuation(self): # https://github.com/giampaolo/psutil/issues/1007 with mock.patch('psutil._pswindows.cext.boot_time', return_value=5): self.assertEqual(psutil.boot_time(), 5) with mock.patch('psutil._pswindows.cext.boot_time', return_value=4): self.assertEqual(psutil.boot_time(), 5) with mock.patch('psutil._pswindows.cext.boot_time', return_value=6): self.assertEqual(psutil.boot_time(), 5) with mock.patch('psutil._pswindows.cext.boot_time', return_value=333): self.assertEqual(psutil.boot_time(), 333) # =================================================================== # sensors_battery() # =================================================================== @unittest.skipIf(not WINDOWS, "WINDOWS only") class TestSensorsBattery(unittest.TestCase): def test_has_battery(self): if win32api.GetPwrCapabilities()['SystemBatteriesPresent']: self.assertIsNotNone(psutil.sensors_battery()) else: self.assertIsNone(psutil.sensors_battery()) @unittest.skipIf(not HAS_BATTERY, "no battery") def test_percent(self): w = wmi.WMI() battery_wmi = w.query('select * from Win32_Battery')[0] battery_psutil = psutil.sensors_battery() self.assertAlmostEqual( battery_psutil.percent, battery_wmi.EstimatedChargeRemaining, delta=1) @unittest.skipIf(not HAS_BATTERY, "no battery") def test_power_plugged(self): w = wmi.WMI() battery_wmi = w.query('select * from Win32_Battery')[0] battery_psutil = psutil.sensors_battery() # Status codes: # https://msdn.microsoft.com/en-us/library/aa394074(v=vs.85).aspx self.assertEqual(battery_psutil.power_plugged, battery_wmi.BatteryStatus == 2) def test_emulate_no_battery(self): with mock.patch("psutil._pswindows.cext.sensors_battery", return_value=(0, 128, 0, 0)) as m: self.assertIsNone(psutil.sensors_battery()) assert m.called def test_emulate_power_connected(self): with mock.patch("psutil._pswindows.cext.sensors_battery", return_value=(1, 0, 0, 0)) as m: self.assertEqual(psutil.sensors_battery().secsleft, psutil.POWER_TIME_UNLIMITED) assert m.called def test_emulate_power_charging(self): with mock.patch("psutil._pswindows.cext.sensors_battery", return_value=(0, 8, 0, 0)) as m: self.assertEqual(psutil.sensors_battery().secsleft, psutil.POWER_TIME_UNLIMITED) assert m.called def test_emulate_secs_left_unknown(self): with mock.patch("psutil._pswindows.cext.sensors_battery", return_value=(0, 0, 0, -1)) as m: self.assertEqual(psutil.sensors_battery().secsleft, psutil.POWER_TIME_UNKNOWN) assert m.called # =================================================================== # Process APIs # =================================================================== @unittest.skipIf(not WINDOWS, "WINDOWS only") class TestProcess(unittest.TestCase): @classmethod def setUpClass(cls): cls.pid = get_test_subprocess().pid @classmethod def tearDownClass(cls): reap_children() def test_issue_24(self): p = psutil.Process(0) self.assertRaises(psutil.AccessDenied, p.kill) def test_special_pid(self): p = psutil.Process(4) self.assertEqual(p.name(), 'System') # use __str__ to access all common Process properties to check # that nothing strange happens str(p) p.username() self.assertTrue(p.create_time() >= 0.0) try: rss, vms = p.memory_info()[:2] except psutil.AccessDenied: # expected on Windows Vista and Windows 7 if not platform.uname()[1] in ('vista', 'win-7', 'win7'): raise else: self.assertTrue(rss > 0) def test_send_signal(self): p = psutil.Process(self.pid) self.assertRaises(ValueError, p.send_signal, signal.SIGINT) def test_exe(self): for p in psutil.process_iter(): try: self.assertEqual(os.path.basename(p.exe()), p.name()) except psutil.Error: pass def test_num_handles_increment(self): p = psutil.Process(os.getpid()) before = p.num_handles() handle = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION, win32con.FALSE, os.getpid()) after = p.num_handles() self.assertEqual(after, before + 1) win32api.CloseHandle(handle) self.assertEqual(p.num_handles(), before) def test_handles_leak(self): # Call all Process methods and make sure no handles are left # open. This is here mainly to make sure functions using # OpenProcess() always call CloseHandle(). def call(p, attr): attr = getattr(p, name, None) if attr is not None and callable(attr): attr() else: attr p = psutil.Process(self.pid) failures = [] for name in dir(psutil.Process): if name.startswith('_') \ or name in ('terminate', 'kill', 'suspend', 'resume', 'nice', 'send_signal', 'wait', 'children', 'as_dict', 'memory_info_ex'): continue else: try: call(p, name) num1 = p.num_handles() call(p, name) num2 = p.num_handles() except (psutil.NoSuchProcess, psutil.AccessDenied): pass else: if num2 > num1: fail = \ "failure while processing Process.%s method " \ "(before=%s, after=%s)" % (name, num1, num2) failures.append(fail) if failures: self.fail('\n' + '\n'.join(failures)) def test_name_always_available(self): # On Windows name() is never supposed to raise AccessDenied, # see https://github.com/giampaolo/psutil/issues/627 for p in psutil.process_iter(): try: p.name() except psutil.NoSuchProcess: pass @unittest.skipIf(not sys.version_info >= (2, 7), "CTRL_* signals not supported") def test_ctrl_signals(self): p = psutil.Process(get_test_subprocess().pid) p.send_signal(signal.CTRL_C_EVENT) p.send_signal(signal.CTRL_BREAK_EVENT) p.kill() p.wait() self.assertRaises(psutil.NoSuchProcess, p.send_signal, signal.CTRL_C_EVENT) self.assertRaises(psutil.NoSuchProcess, p.send_signal, signal.CTRL_BREAK_EVENT) def test_compare_name_exe(self): for p in psutil.process_iter(): try: a = os.path.basename(p.exe()) b = p.name() except (psutil.NoSuchProcess, psutil.AccessDenied): pass else: self.assertEqual(a, b) def test_username(self): self.assertEqual(psutil.Process().username(), win32api.GetUserNameEx(win32con.NameSamCompatible)) def test_cmdline(self): sys_value = re.sub(' +', ' ', win32api.GetCommandLine()).strip() psutil_value = ' '.join(psutil.Process().cmdline()) self.assertEqual(sys_value, psutil_value) # XXX - occasional failures # def test_cpu_times(self): # handle = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION, # win32con.FALSE, os.getpid()) # self.addCleanup(win32api.CloseHandle, handle) # sys_value = win32process.GetProcessTimes(handle) # psutil_value = psutil.Process().cpu_times() # self.assertAlmostEqual( # psutil_value.user, sys_value['UserTime'] / 10000000.0, # delta=0.2) # self.assertAlmostEqual( # psutil_value.user, sys_value['KernelTime'] / 10000000.0, # delta=0.2) def test_nice(self): handle = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION, win32con.FALSE, os.getpid()) self.addCleanup(win32api.CloseHandle, handle) sys_value = win32process.GetPriorityClass(handle) psutil_value = psutil.Process().nice() self.assertEqual(psutil_value, sys_value) def test_memory_info(self): handle = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION, win32con.FALSE, self.pid) self.addCleanup(win32api.CloseHandle, handle) sys_value = win32process.GetProcessMemoryInfo(handle) psutil_value = psutil.Process(self.pid).memory_info() self.assertEqual( sys_value['PeakWorkingSetSize'], psutil_value.peak_wset) self.assertEqual( sys_value['WorkingSetSize'], psutil_value.wset) self.assertEqual( sys_value['QuotaPeakPagedPoolUsage'], psutil_value.peak_paged_pool) self.assertEqual( sys_value['QuotaPagedPoolUsage'], psutil_value.paged_pool) self.assertEqual( sys_value['QuotaPeakNonPagedPoolUsage'], psutil_value.peak_nonpaged_pool) self.assertEqual( sys_value['QuotaNonPagedPoolUsage'], psutil_value.nonpaged_pool) self.assertEqual( sys_value['PagefileUsage'], psutil_value.pagefile) self.assertEqual( sys_value['PeakPagefileUsage'], psutil_value.peak_pagefile) self.assertEqual(psutil_value.rss, psutil_value.wset) self.assertEqual(psutil_value.vms, psutil_value.pagefile) def test_wait(self): handle = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION, win32con.FALSE, self.pid) self.addCleanup(win32api.CloseHandle, handle) p = psutil.Process(self.pid) p.terminate() psutil_value = p.wait() sys_value = win32process.GetExitCodeProcess(handle) self.assertEqual(psutil_value, sys_value) def test_cpu_affinity(self): def from_bitmask(x): return [i for i in range(64) if (1 << i) & x] handle = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION, win32con.FALSE, self.pid) self.addCleanup(win32api.CloseHandle, handle) sys_value = from_bitmask( win32process.GetProcessAffinityMask(handle)[0]) psutil_value = psutil.Process(self.pid).cpu_affinity() self.assertEqual(psutil_value, sys_value) def test_io_counters(self): handle = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION, win32con.FALSE, os.getpid()) self.addCleanup(win32api.CloseHandle, handle) sys_value = win32process.GetProcessIoCounters(handle) psutil_value = psutil.Process().io_counters() self.assertEqual( psutil_value.read_count, sys_value['ReadOperationCount']) self.assertEqual( psutil_value.write_count, sys_value['WriteOperationCount']) self.assertEqual( psutil_value.read_bytes, sys_value['ReadTransferCount']) self.assertEqual( psutil_value.write_bytes, sys_value['WriteTransferCount']) self.assertEqual( psutil_value.other_count, sys_value['OtherOperationCount']) self.assertEqual( psutil_value.other_bytes, sys_value['OtherTransferCount']) def test_num_handles(self): import ctypes import ctypes.wintypes PROCESS_QUERY_INFORMATION = 0x400 handle = ctypes.windll.kernel32.OpenProcess( PROCESS_QUERY_INFORMATION, 0, os.getpid()) self.addCleanup(ctypes.windll.kernel32.CloseHandle, handle) hndcnt = ctypes.wintypes.DWORD() ctypes.windll.kernel32.GetProcessHandleCount( handle, ctypes.byref(hndcnt)) sys_value = hndcnt.value psutil_value = psutil.Process().num_handles() ctypes.windll.kernel32.CloseHandle(handle) self.assertEqual(psutil_value, sys_value + 1) @unittest.skipIf(not WINDOWS, "WINDOWS only") class TestProcessWMI(unittest.TestCase): """Compare Process API results with WMI.""" @classmethod def setUpClass(cls): cls.pid = get_test_subprocess().pid @classmethod def tearDownClass(cls): reap_children() def test_name(self): w = wmi.WMI().Win32_Process(ProcessId=self.pid)[0] p = psutil.Process(self.pid) self.assertEqual(p.name(), w.Caption) def test_exe(self): w = wmi.WMI().Win32_Process(ProcessId=self.pid)[0] p = psutil.Process(self.pid) # Note: wmi reports the exe as a lower case string. # Being Windows paths case-insensitive we ignore that. self.assertEqual(p.exe().lower(), w.ExecutablePath.lower()) def test_cmdline(self): w = wmi.WMI().Win32_Process(ProcessId=self.pid)[0] p = psutil.Process(self.pid) self.assertEqual(' '.join(p.cmdline()), w.CommandLine.replace('"', '')) def test_username(self): w = wmi.WMI().Win32_Process(ProcessId=self.pid)[0] p = psutil.Process(self.pid) domain, _, username = w.GetOwner() username = "%s\\%s" % (domain, username) self.assertEqual(p.username(), username) def test_memory_rss(self): time.sleep(0.1) w = wmi.WMI().Win32_Process(ProcessId=self.pid)[0] p = psutil.Process(self.pid) rss = p.memory_info().rss self.assertEqual(rss, int(w.WorkingSetSize)) def test_memory_vms(self): time.sleep(0.1) w = wmi.WMI().Win32_Process(ProcessId=self.pid)[0] p = psutil.Process(self.pid) vms = p.memory_info().vms # http://msdn.microsoft.com/en-us/library/aa394372(VS.85).aspx # ...claims that PageFileUsage is represented in Kilo # bytes but funnily enough on certain platforms bytes are # returned instead. wmi_usage = int(w.PageFileUsage) if (vms != wmi_usage) and (vms != wmi_usage * 1024): self.fail("wmi=%s, psutil=%s" % (wmi_usage, vms)) def test_create_time(self): w = wmi.WMI().Win32_Process(ProcessId=self.pid)[0] p = psutil.Process(self.pid) wmic_create = str(w.CreationDate.split('.')[0]) psutil_create = time.strftime("%Y%m%d%H%M%S", time.localtime(p.create_time())) self.assertEqual(wmic_create, psutil_create) @unittest.skipIf(not WINDOWS, "WINDOWS only") class TestDualProcessImplementation(unittest.TestCase): """ Certain APIs on Windows have 2 internal implementations, one based on documented Windows APIs, another one based NtQuerySystemInformation() which gets called as fallback in case the first fails because of limited permission error. Here we test that the two methods return the exact same value, see: https://github.com/giampaolo/psutil/issues/304 """ @classmethod def setUpClass(cls): cls.pid = get_test_subprocess().pid @classmethod def tearDownClass(cls): reap_children() # --- # same tests as above but mimicks the AccessDenied failure of # the first (fast) method failing with AD. def test_name(self): name = psutil.Process(self.pid).name() with mock.patch("psutil._psplatform.cext.proc_exe", side_effect=psutil.AccessDenied(os.getpid())) as fun: self.assertEqual(psutil.Process(self.pid).name(), name) assert fun.called def test_memory_info(self): mem_1 = psutil.Process(self.pid).memory_info() with mock.patch("psutil._psplatform.cext.proc_memory_info", side_effect=OSError(errno.EPERM, "msg")) as fun: mem_2 = psutil.Process(self.pid).memory_info() self.assertEqual(len(mem_1), len(mem_2)) for i in range(len(mem_1)): self.assertGreaterEqual(mem_1[i], 0) self.assertGreaterEqual(mem_2[i], 0) self.assertAlmostEqual(mem_1[i], mem_2[i], delta=512) assert fun.called def test_create_time(self): ctime = psutil.Process(self.pid).create_time() with mock.patch("psutil._psplatform.cext.proc_create_time", side_effect=OSError(errno.EPERM, "msg")) as fun: self.assertEqual(psutil.Process(self.pid).create_time(), ctime) assert fun.called def test_cpu_times(self): cpu_times_1 = psutil.Process(self.pid).cpu_times() with mock.patch("psutil._psplatform.cext.proc_cpu_times", side_effect=OSError(errno.EPERM, "msg")) as fun: cpu_times_2 = psutil.Process(self.pid).cpu_times() assert fun.called self.assertAlmostEqual( cpu_times_1.user, cpu_times_2.user, delta=0.01) self.assertAlmostEqual( cpu_times_1.system, cpu_times_2.system, delta=0.01) def test_io_counters(self): io_counters_1 = psutil.Process(self.pid).io_counters() with mock.patch("psutil._psplatform.cext.proc_io_counters", side_effect=OSError(errno.EPERM, "msg")) as fun: io_counters_2 = psutil.Process(self.pid).io_counters() for i in range(len(io_counters_1)): self.assertAlmostEqual( io_counters_1[i], io_counters_2[i], delta=5) assert fun.called def test_num_handles(self): num_handles = psutil.Process(self.pid).num_handles() with mock.patch("psutil._psplatform.cext.proc_num_handles", side_effect=OSError(errno.EPERM, "msg")) as fun: self.assertEqual(psutil.Process(self.pid).num_handles(), num_handles) assert fun.called @unittest.skipIf(not WINDOWS, "WINDOWS only") class RemoteProcessTestCase(unittest.TestCase): """Certain functions require calling ReadProcessMemory. This trivially works when called on the current process. Check that this works on other processes, especially when they have a different bitness. """ @staticmethod def find_other_interpreter(): # find a python interpreter that is of the opposite bitness from us code = "import sys; sys.stdout.write(str(sys.maxsize > 2**32))" # XXX: a different and probably more stable approach might be to access # the registry but accessing 64 bit paths from a 32 bit process for filename in glob.glob(r"C:\Python*\python.exe"): proc = subprocess.Popen(args=[filename, "-c", code], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) output, _ = proc.communicate() if output == str(not IS_64_BIT): return filename @classmethod def setUpClass(cls): other_python = cls.find_other_interpreter() if other_python is None: raise unittest.SkipTest( "could not find interpreter with opposite bitness") if IS_64_BIT: cls.python64 = sys.executable cls.python32 = other_python else: cls.python64 = other_python cls.python32 = sys.executable test_args = ["-c", "import sys; sys.stdin.read()"] def setUp(self): env = os.environ.copy() env["THINK_OF_A_NUMBER"] = str(os.getpid()) self.proc32 = get_test_subprocess([self.python32] + self.test_args, env=env, stdin=subprocess.PIPE) self.proc64 = get_test_subprocess([self.python64] + self.test_args, env=env, stdin=subprocess.PIPE) def tearDown(self): self.proc32.communicate() self.proc64.communicate() reap_children() @classmethod def tearDownClass(cls): reap_children() def test_cmdline_32(self): p = psutil.Process(self.proc32.pid) self.assertEqual(len(p.cmdline()), 3) self.assertEqual(p.cmdline()[1:], self.test_args) def test_cmdline_64(self): p = psutil.Process(self.proc64.pid) self.assertEqual(len(p.cmdline()), 3) self.assertEqual(p.cmdline()[1:], self.test_args) def test_cwd_32(self): p = psutil.Process(self.proc32.pid) self.assertEqual(p.cwd(), os.getcwd()) def test_cwd_64(self): p = psutil.Process(self.proc64.pid) self.assertEqual(p.cwd(), os.getcwd()) def test_environ_32(self): p = psutil.Process(self.proc32.pid) e = p.environ() self.assertIn("THINK_OF_A_NUMBER", e) self.assertEquals(e["THINK_OF_A_NUMBER"], str(os.getpid())) def test_environ_64(self): p = psutil.Process(self.proc64.pid) e = p.environ() self.assertIn("THINK_OF_A_NUMBER", e) self.assertEquals(e["THINK_OF_A_NUMBER"], str(os.getpid())) # =================================================================== # Windows services # =================================================================== @unittest.skipIf(not WINDOWS, "WINDOWS only") class TestServices(unittest.TestCase): def test_win_service_iter(self): valid_statuses = set([ "running", "paused", "start", "pause", "continue", "stop", "stopped", ]) valid_start_types = set([ "automatic", "manual", "disabled", ]) valid_statuses = set([ "running", "paused", "start_pending", "pause_pending", "continue_pending", "stop_pending", "stopped" ]) for serv in psutil.win_service_iter(): data = serv.as_dict() self.assertIsInstance(data['name'], str) self.assertNotEqual(data['name'].strip(), "") self.assertIsInstance(data['display_name'], str) self.assertIsInstance(data['username'], str) self.assertIn(data['status'], valid_statuses) if data['pid'] is not None: psutil.Process(data['pid']) self.assertIsInstance(data['binpath'], str) self.assertIsInstance(data['username'], str) self.assertIsInstance(data['start_type'], str) self.assertIn(data['start_type'], valid_start_types) self.assertIn(data['status'], valid_statuses) self.assertIsInstance(data['description'], str) pid = serv.pid() if pid is not None: p = psutil.Process(pid) self.assertTrue(p.is_running()) # win_service_get s = psutil.win_service_get(serv.name()) # test __eq__ self.assertEqual(serv, s) def test_win_service_get(self): name = next(psutil.win_service_iter()).name() with self.assertRaises(psutil.NoSuchProcess) as cm: psutil.win_service_get(name + '???') self.assertEqual(cm.exception.name, name + '???') # test NoSuchProcess service = psutil.win_service_get(name) exc = WindowsError( psutil._psplatform.cext.ERROR_SERVICE_DOES_NOT_EXIST, "") with mock.patch("psutil._psplatform.cext.winservice_query_status", side_effect=exc): self.assertRaises(psutil.NoSuchProcess, service.status) with mock.patch("psutil._psplatform.cext.winservice_query_config", side_effect=exc): self.assertRaises(psutil.NoSuchProcess, service.username) # test AccessDenied exc = WindowsError( psutil._psplatform.cext.ERROR_ACCESS_DENIED, "") with mock.patch("psutil._psplatform.cext.winservice_query_status", side_effect=exc): self.assertRaises(psutil.AccessDenied, service.status) with mock.patch("psutil._psplatform.cext.winservice_query_config", side_effect=exc): self.assertRaises(psutil.AccessDenied, service.username) # test __str__ and __repr__ self.assertIn(service.name(), str(service)) self.assertIn(service.display_name(), str(service)) self.assertIn(service.name(), repr(service)) self.assertIn(service.display_name(), repr(service)) if __name__ == '__main__': run_test_module_by_name(__file__) PK![2[2test_unicode.pynu[# -*- coding: utf-8 -*- # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Notes about unicode handling in psutil ====================================== In psutil these are the APIs returning or dealing with a string ('not tested' means they are not tested to deal with non-ASCII strings): * Process.cmdline() * Process.connections('unix') * Process.cwd() * Process.environ() * Process.exe() * Process.memory_maps() * Process.name() * Process.open_files() * Process.username() (not tested) * disk_io_counters() (not tested) * disk_partitions() (not tested) * disk_usage(str) * net_connections('unix') * net_if_addrs() (not tested) * net_if_stats() (not tested) * net_io_counters() (not tested) * sensors_fans() (not tested) * sensors_temperatures() (not tested) * users() (not tested) * WindowsService.binpath() (not tested) * WindowsService.description() (not tested) * WindowsService.display_name() (not tested) * WindowsService.name() (not tested) * WindowsService.status() (not tested) * WindowsService.username() (not tested) In here we create a unicode path with a funky non-ASCII name and (where possible) make psutil return it back (e.g. on name(), exe(), open_files(), etc.) and make sure that: * psutil never crashes with UnicodeDecodeError * the returned path matches For a detailed explanation of how psutil handles unicode see: - https://github.com/giampaolo/psutil/issues/1040 - http://psutil.readthedocs.io/#unicode """ import os import traceback import warnings from contextlib import closing from psutil import BSD from psutil import OPENBSD from psutil import OSX from psutil import POSIX from psutil import WINDOWS from psutil._compat import PY3 from psutil._compat import u from psutil.tests import APPVEYOR from psutil.tests import ASCII_FS from psutil.tests import bind_unix_socket from psutil.tests import chdir from psutil.tests import copyload_shared_lib from psutil.tests import create_exe from psutil.tests import get_test_subprocess from psutil.tests import HAS_CONNECTIONS_UNIX from psutil.tests import HAS_ENVIRON from psutil.tests import HAS_MEMORY_MAPS from psutil.tests import mock from psutil.tests import reap_children from psutil.tests import run_test_module_by_name from psutil.tests import safe_mkdir from psutil.tests import safe_rmpath as _safe_rmpath from psutil.tests import skip_on_access_denied from psutil.tests import TESTFILE_PREFIX from psutil.tests import TESTFN from psutil.tests import TESTFN_UNICODE from psutil.tests import TRAVIS from psutil.tests import unittest from psutil.tests import unix_socket_path import psutil import psutil.tests def safe_rmpath(path): if APPVEYOR: # TODO - this is quite random and I'm not sure why it happens, # nor I can reproduce it locally: # https://ci.appveyor.com/project/giampaolo/psutil/build/job/ # jiq2cgd6stsbtn60 # safe_rmpath() happens after reap_children() so this is weird # Perhaps wait_procs() on Windows is broken? Maybe because # of STILL_ACTIVE? # https://github.com/giampaolo/psutil/blob/ # 68c7a70728a31d8b8b58f4be6c4c0baa2f449eda/psutil/arch/ # windows/process_info.c#L146 try: return _safe_rmpath(path) except WindowsError: traceback.print_exc() else: return _safe_rmpath(path) def subprocess_supports_unicode(name): """Return True if both the fs and the subprocess module can deal with a unicode file name. """ if PY3: return True try: safe_rmpath(name) create_exe(name) get_test_subprocess(cmd=[name]) except UnicodeEncodeError: return False else: return True finally: reap_children() # An invalid unicode string. if PY3: INVALID_NAME = (TESTFN.encode('utf8') + b"f\xc0\x80").decode( 'utf8', 'surrogateescape') else: INVALID_NAME = TESTFN + "f\xc0\x80" # =================================================================== # FS APIs # =================================================================== class _BaseFSAPIsTests(object): funky_name = None @classmethod def setUpClass(cls): safe_rmpath(cls.funky_name) create_exe(cls.funky_name) @classmethod def tearDownClass(cls): reap_children() safe_rmpath(cls.funky_name) def tearDown(self): reap_children() def expect_exact_path_match(self): raise NotImplementedError("must be implemented in subclass") def test_proc_exe(self): subp = get_test_subprocess(cmd=[self.funky_name]) p = psutil.Process(subp.pid) exe = p.exe() self.assertIsInstance(exe, str) if self.expect_exact_path_match(): self.assertEqual(exe, self.funky_name) def test_proc_name(self): subp = get_test_subprocess(cmd=[self.funky_name]) if WINDOWS: # On Windows name() is determined from exe() first, because # it's faster; we want to overcome the internal optimization # and test name() instead of exe(). with mock.patch("psutil._psplatform.cext.proc_exe", side_effect=psutil.AccessDenied(os.getpid())) as m: name = psutil.Process(subp.pid).name() assert m.called else: name = psutil.Process(subp.pid).name() self.assertIsInstance(name, str) if self.expect_exact_path_match(): self.assertEqual(name, os.path.basename(self.funky_name)) def test_proc_cmdline(self): subp = get_test_subprocess(cmd=[self.funky_name]) p = psutil.Process(subp.pid) cmdline = p.cmdline() for part in cmdline: self.assertIsInstance(part, str) if self.expect_exact_path_match(): self.assertEqual(cmdline, [self.funky_name]) def test_proc_cwd(self): dname = self.funky_name + "2" self.addCleanup(safe_rmpath, dname) safe_mkdir(dname) with chdir(dname): p = psutil.Process() cwd = p.cwd() self.assertIsInstance(p.cwd(), str) if self.expect_exact_path_match(): self.assertEqual(cwd, dname) def test_proc_open_files(self): p = psutil.Process() start = set(p.open_files()) with open(self.funky_name, 'rb'): new = set(p.open_files()) path = (new - start).pop().path self.assertIsInstance(path, str) if BSD and not path: # XXX - see https://github.com/giampaolo/psutil/issues/595 return self.skipTest("open_files on BSD is broken") if self.expect_exact_path_match(): self.assertEqual(os.path.normcase(path), os.path.normcase(self.funky_name)) @unittest.skipIf(not POSIX, "POSIX only") def test_proc_connections(self): suffix = os.path.basename(self.funky_name) with unix_socket_path(suffix=suffix) as name: try: sock = bind_unix_socket(name) except UnicodeEncodeError: if PY3: raise else: raise unittest.SkipTest("not supported") with closing(sock): conn = psutil.Process().connections('unix')[0] self.assertIsInstance(conn.laddr, str) # AF_UNIX addr not set on OpenBSD if not OPENBSD: self.assertEqual(conn.laddr, name) @unittest.skipIf(not POSIX, "POSIX only") @unittest.skipIf(not HAS_CONNECTIONS_UNIX, "can't list UNIX sockets") @skip_on_access_denied() def test_net_connections(self): def find_sock(cons): for conn in cons: if os.path.basename(conn.laddr).startswith(TESTFILE_PREFIX): return conn raise ValueError("connection not found") suffix = os.path.basename(self.funky_name) with unix_socket_path(suffix=suffix) as name: try: sock = bind_unix_socket(name) except UnicodeEncodeError: if PY3: raise else: raise unittest.SkipTest("not supported") with closing(sock): cons = psutil.net_connections(kind='unix') # AF_UNIX addr not set on OpenBSD if not OPENBSD: conn = find_sock(cons) self.assertIsInstance(conn.laddr, str) self.assertEqual(conn.laddr, name) def test_disk_usage(self): dname = self.funky_name + "2" self.addCleanup(safe_rmpath, dname) safe_mkdir(dname) psutil.disk_usage(dname) @unittest.skipIf(not HAS_MEMORY_MAPS, "not supported") @unittest.skipIf(not PY3, "ctypes does not support unicode on PY2") def test_memory_maps(self): # XXX: on Python 2, using ctypes.CDLL with a unicode path # opens a message box which blocks the test run. with copyload_shared_lib(dst_prefix=self.funky_name) as funky_path: def normpath(p): return os.path.realpath(os.path.normcase(p)) libpaths = [normpath(x.path) for x in psutil.Process().memory_maps()] # ...just to have a clearer msg in case of failure libpaths = [x for x in libpaths if TESTFILE_PREFIX in x] self.assertIn(normpath(funky_path), libpaths) for path in libpaths: self.assertIsInstance(path, str) @unittest.skipIf(OSX and TRAVIS, "unreliable on TRAVIS") # TODO @unittest.skipIf(ASCII_FS, "ASCII fs") @unittest.skipIf(not subprocess_supports_unicode(TESTFN_UNICODE), "subprocess can't deal with unicode") class TestFSAPIs(_BaseFSAPIsTests, unittest.TestCase): """Test FS APIs with a funky, valid, UTF8 path name.""" funky_name = TESTFN_UNICODE @classmethod def expect_exact_path_match(cls): # Do not expect psutil to correctly handle unicode paths on # Python 2 if os.listdir() is not able either. if PY3: return True else: here = '.' if isinstance(cls.funky_name, str) else u('.') with warnings.catch_warnings(): warnings.simplefilter("ignore") return cls.funky_name in os.listdir(here) @unittest.skipIf(OSX and TRAVIS, "unreliable on TRAVIS") # TODO @unittest.skipIf(not subprocess_supports_unicode(INVALID_NAME), "subprocess can't deal with invalid unicode") class TestFSAPIsWithInvalidPath(_BaseFSAPIsTests, unittest.TestCase): """Test FS APIs with a funky, invalid path name.""" funky_name = INVALID_NAME @classmethod def expect_exact_path_match(cls): # Invalid unicode names are supposed to work on Python 2. return True @unittest.skipIf(not WINDOWS, "WINDOWS only") class TestWinProcessName(unittest.TestCase): def test_name_type(self): # On Windows name() is determined from exe() first, because # it's faster; we want to overcome the internal optimization # and test name() instead of exe(). with mock.patch("psutil._psplatform.cext.proc_exe", side_effect=psutil.AccessDenied(os.getpid())) as m: self.assertIsInstance(psutil.Process().name(), str) assert m.called # =================================================================== # Non fs APIs # =================================================================== class TestNonFSAPIS(unittest.TestCase): """Unicode tests for non fs-related APIs.""" def tearDown(self): reap_children() @unittest.skipIf(not HAS_ENVIRON, "not supported") def test_proc_environ(self): # Note: differently from others, this test does not deal # with fs paths. On Python 2 subprocess module is broken as # it's not able to handle with non-ASCII env vars, so # we use "è", which is part of the extended ASCII table # (unicode point <= 255). env = os.environ.copy() funky_str = TESTFN_UNICODE if PY3 else 'è' env['FUNNY_ARG'] = funky_str sproc = get_test_subprocess(env=env) p = psutil.Process(sproc.pid) env = p.environ() for k, v in env.items(): self.assertIsInstance(k, str) self.assertIsInstance(v, str) self.assertEqual(env['FUNNY_ARG'], funky_str) if __name__ == '__main__': run_test_module_by_name(__file__) PK!XAmm test_aix.pynu[ # Copyright (c) 2009, Giampaolo Rodola' # Copyright (c) 2017, Arnon Yaari # All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """AIX specific tests.""" import re from psutil import AIX from psutil.tests import run_test_module_by_name from psutil.tests import sh from psutil.tests import unittest import psutil @unittest.skipIf(not AIX, "AIX only") class AIXSpecificTestCase(unittest.TestCase): def test_virtual_memory(self): out = sh('/usr/bin/svmon -O unit=KB') re_pattern = "memory\s*" for field in ("size inuse free pin virtual available mmode").split(): re_pattern += "(?P<%s>\S+)\s+" % (field,) matchobj = re.search(re_pattern, out) self.assertIsNotNone( matchobj, "svmon command returned unexpected output") KB = 1024 total = int(matchobj.group("size")) * KB available = int(matchobj.group("available")) * KB used = int(matchobj.group("inuse")) * KB free = int(matchobj.group("free")) * KB psutil_result = psutil.virtual_memory() # MEMORY_TOLERANCE from psutil.tests is not enough. For some reason # we're seeing differences of ~1.2 MB. 2 MB is still a good tolerance # when compared to GBs. MEMORY_TOLERANCE = 2 * KB * KB # 2 MB self.assertEqual(psutil_result.total, total) self.assertAlmostEqual( psutil_result.used, used, delta=MEMORY_TOLERANCE) self.assertAlmostEqual( psutil_result.available, available, delta=MEMORY_TOLERANCE) self.assertAlmostEqual( psutil_result.free, free, delta=MEMORY_TOLERANCE) def test_swap_memory(self): out = sh('/usr/sbin/lsps -a') # From the man page, "The size is given in megabytes" so we assume # we'll always have 'MB' in the result # TODO maybe try to use "swap -l" to check "used" too, but its units # are not guaranteed to be "MB" so parsing may not be consistent matchobj = re.search("(?P\S+)\s+" "(?P\S+)\s+" "(?P\S+)\s+" "(?P\d+)MB", out) self.assertIsNotNone( matchobj, "lsps command returned unexpected output") total_mb = int(matchobj.group("size")) MB = 1024 ** 2 psutil_result = psutil.swap_memory() # we divide our result by MB instead of multiplying the lsps value by # MB because lsps may round down, so we round down too self.assertEqual(int(psutil_result.total / MB), total_mb) def test_cpu_stats(self): out = sh('/usr/bin/mpstat -a') re_pattern = "ALL\s*" for field in ("min maj mpcs mpcr dev soft dec ph cs ics bound rq " "push S3pull S3grd S0rd S1rd S2rd S3rd S4rd S5rd " "sysc").split(): re_pattern += "(?P<%s>\S+)\s+" % (field,) matchobj = re.search(re_pattern, out) self.assertIsNotNone( matchobj, "mpstat command returned unexpected output") # numbers are usually in the millions so 1000 is ok for tolerance CPU_STATS_TOLERANCE = 1000 psutil_result = psutil.cpu_stats() self.assertAlmostEqual( psutil_result.ctx_switches, int(matchobj.group("cs")), delta=CPU_STATS_TOLERANCE) self.assertAlmostEqual( psutil_result.syscalls, int(matchobj.group("sysc")), delta=CPU_STATS_TOLERANCE) self.assertAlmostEqual( psutil_result.interrupts, int(matchobj.group("dev")), delta=CPU_STATS_TOLERANCE) self.assertAlmostEqual( psutil_result.soft_interrupts, int(matchobj.group("soft")), delta=CPU_STATS_TOLERANCE) def test_cpu_count_logical(self): out = sh('/usr/bin/mpstat -a') mpstat_lcpu = int(re.search("lcpu=(\d+)", out).group(1)) psutil_lcpu = psutil.cpu_count(logical=True) self.assertEqual(mpstat_lcpu, psutil_lcpu) def test_net_if_addrs_names(self): out = sh('/etc/ifconfig -l') ifconfig_names = set(out.split()) psutil_names = set(psutil.net_if_addrs().keys()) self.assertSetEqual(ifconfig_names, psutil_names) if __name__ == '__main__': run_test_module_by_name(__file__) PK!,g __main__.pynu[ # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Run unit tests. This is invoked by: $ python -m psutil.tests """ import contextlib import optparse import os import ssl import sys import tempfile try: from urllib.request import urlopen # py3 except ImportError: from urllib2 import urlopen from psutil.tests import PYTHON_EXE from psutil.tests import run_suite HERE = os.path.abspath(os.path.dirname(__file__)) GET_PIP_URL = "https://bootstrap.pypa.io/get-pip.py" TEST_DEPS = [] if sys.version_info[:2] == (2, 6): TEST_DEPS.extend(["ipaddress", "unittest2", "argparse", "mock==1.0.1"]) elif sys.version_info[:2] == (2, 7) or sys.version_info[:2] <= (3, 2): TEST_DEPS.extend(["ipaddress", "mock"]) elif sys.version_info[:2] == (3, 3): TEST_DEPS.extend(["ipaddress"]) def install_pip(): try: import pip # NOQA except ImportError: f = tempfile.NamedTemporaryFile(suffix='.py') with contextlib.closing(f): print("downloading %s to %s" % (GET_PIP_URL, f.name)) if hasattr(ssl, '_create_unverified_context'): ctx = ssl._create_unverified_context() else: ctx = None kwargs = dict(context=ctx) if ctx else {} req = urlopen(GET_PIP_URL, **kwargs) data = req.read() f.write(data) f.flush() print("installing pip") code = os.system('%s %s --user' % (PYTHON_EXE, f.name)) return code def install_test_deps(deps=None): """Install test dependencies via pip.""" if deps is None: deps = TEST_DEPS deps = set(deps) if deps: is_venv = hasattr(sys, 'real_prefix') opts = "--user" if not is_venv else "" install_pip() code = os.system('%s -m pip install %s --upgrade %s' % ( PYTHON_EXE, opts, " ".join(deps))) return code def main(): usage = "%s -m psutil.tests [opts]" % PYTHON_EXE parser = optparse.OptionParser(usage=usage, description="run unit tests") parser.add_option("-i", "--install-deps", action="store_true", default=False, help="don't print status messages to stdout") opts, args = parser.parse_args() if opts.install_deps: install_pip() install_test_deps() else: for dep in TEST_DEPS: try: __import__(dep.split("==")[0]) except ImportError: sys.exit("%r lib is not installed; run %s -m psutil.tests " "--install-deps" % (dep, PYTHON_EXE)) run_suite() main() PK!1 33 test_linux.pynu[ # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Linux specific tests.""" from __future__ import division import collections import contextlib import errno import glob import io import os import pprint import re import shutil import socket import struct import tempfile import textwrap import time import warnings import psutil from psutil import LINUX from psutil._compat import PY3 from psutil._compat import u from psutil.tests import call_until from psutil.tests import HAS_BATTERY from psutil.tests import HAS_CPU_FREQ from psutil.tests import HAS_RLIMIT from psutil.tests import MEMORY_TOLERANCE from psutil.tests import mock from psutil.tests import PYPY from psutil.tests import pyrun from psutil.tests import reap_children from psutil.tests import reload_module from psutil.tests import retry_before_failing from psutil.tests import run_test_module_by_name from psutil.tests import safe_rmpath from psutil.tests import sh from psutil.tests import skip_on_not_implemented from psutil.tests import TESTFN from psutil.tests import ThreadTask from psutil.tests import TRAVIS from psutil.tests import unittest from psutil.tests import which HERE = os.path.abspath(os.path.dirname(__file__)) SIOCGIFADDR = 0x8915 SIOCGIFCONF = 0x8912 SIOCGIFHWADDR = 0x8927 if LINUX: SECTOR_SIZE = 512 # ===================================================================== # --- utils # ===================================================================== def get_ipv4_address(ifname): import fcntl ifname = ifname[:15] if PY3: ifname = bytes(ifname, 'ascii') s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) with contextlib.closing(s): return socket.inet_ntoa( fcntl.ioctl(s.fileno(), SIOCGIFADDR, struct.pack('256s', ifname))[20:24]) def get_mac_address(ifname): import fcntl ifname = ifname[:15] if PY3: ifname = bytes(ifname, 'ascii') s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) with contextlib.closing(s): info = fcntl.ioctl( s.fileno(), SIOCGIFHWADDR, struct.pack('256s', ifname)) if PY3: def ord(x): return x else: import __builtin__ ord = __builtin__.ord return ''.join(['%02x:' % ord(char) for char in info[18:24]])[:-1] def free_swap(): """Parse 'free' cmd and return swap memory's s total, used and free values. """ out = sh('free -b') lines = out.split('\n') for line in lines: if line.startswith('Swap'): _, total, used, free = line.split() nt = collections.namedtuple('free', 'total used free') return nt(int(total), int(used), int(free)) raise ValueError( "can't find 'Swap' in 'free' output:\n%s" % '\n'.join(lines)) def free_physmem(): """Parse 'free' cmd and return physical memory's total, used and free values. """ # Note: free can have 2 different formats, invalidating 'shared' # and 'cached' memory which may have different positions so we # do not return them. # https://github.com/giampaolo/psutil/issues/538#issuecomment-57059946 out = sh('free -b') lines = out.split('\n') for line in lines: if line.startswith('Mem'): total, used, free, shared = \ [int(x) for x in line.split()[1:5]] nt = collections.namedtuple( 'free', 'total used free shared output') return nt(total, used, free, shared, out) raise ValueError( "can't find 'Mem' in 'free' output:\n%s" % '\n'.join(lines)) def vmstat(stat): out = sh("vmstat -s") for line in out.split("\n"): line = line.strip() if stat in line: return int(line.split(' ')[0]) raise ValueError("can't find %r in 'vmstat' output" % stat) def get_free_version_info(): out = sh("free -V").strip() return tuple(map(int, out.split()[-1].split('.'))) # ===================================================================== # --- system virtual memory # ===================================================================== @unittest.skipIf(not LINUX, "LINUX only") class TestSystemVirtualMemory(unittest.TestCase): def test_total(self): # free_value = free_physmem().total # psutil_value = psutil.virtual_memory().total # self.assertEqual(free_value, psutil_value) vmstat_value = vmstat('total memory') * 1024 psutil_value = psutil.virtual_memory().total self.assertAlmostEqual(vmstat_value, psutil_value) # Older versions of procps used slab memory to calculate used memory. # This got changed in: # https://gitlab.com/procps-ng/procps/commit/ # 05d751c4f076a2f0118b914c5e51cfbb4762ad8e @unittest.skipIf(LINUX and get_free_version_info() < (3, 3, 12), "old free version") @retry_before_failing() def test_used(self): free = free_physmem() free_value = free.used psutil_value = psutil.virtual_memory().used self.assertAlmostEqual( free_value, psutil_value, delta=MEMORY_TOLERANCE, msg='%s %s \n%s' % (free_value, psutil_value, free.output)) @unittest.skipIf(TRAVIS, "unreliable on TRAVIS") @retry_before_failing() def test_free(self): # _, _, free_value, _ = free_physmem() # psutil_value = psutil.virtual_memory().free # self.assertAlmostEqual( # free_value, psutil_value, delta=MEMORY_TOLERANCE) vmstat_value = vmstat('free memory') * 1024 psutil_value = psutil.virtual_memory().free self.assertAlmostEqual( vmstat_value, psutil_value, delta=MEMORY_TOLERANCE) @retry_before_failing() def test_buffers(self): vmstat_value = vmstat('buffer memory') * 1024 psutil_value = psutil.virtual_memory().buffers self.assertAlmostEqual( vmstat_value, psutil_value, delta=MEMORY_TOLERANCE) # https://travis-ci.org/giampaolo/psutil/jobs/226719664 @unittest.skipIf(TRAVIS, "unreliable on TRAVIS") @retry_before_failing() def test_active(self): vmstat_value = vmstat('active memory') * 1024 psutil_value = psutil.virtual_memory().active self.assertAlmostEqual( vmstat_value, psutil_value, delta=MEMORY_TOLERANCE) # https://travis-ci.org/giampaolo/psutil/jobs/227242952 @unittest.skipIf(TRAVIS, "unreliable on TRAVIS") @retry_before_failing() def test_inactive(self): vmstat_value = vmstat('inactive memory') * 1024 psutil_value = psutil.virtual_memory().inactive self.assertAlmostEqual( vmstat_value, psutil_value, delta=MEMORY_TOLERANCE) @retry_before_failing() def test_shared(self): free = free_physmem() free_value = free.shared if free_value == 0: raise unittest.SkipTest("free does not support 'shared' column") psutil_value = psutil.virtual_memory().shared self.assertAlmostEqual( free_value, psutil_value, delta=MEMORY_TOLERANCE, msg='%s %s \n%s' % (free_value, psutil_value, free.output)) @retry_before_failing() def test_available(self): # "free" output format has changed at some point: # https://github.com/giampaolo/psutil/issues/538#issuecomment-147192098 out = sh("free -b") lines = out.split('\n') if 'available' not in lines[0]: raise unittest.SkipTest("free does not support 'available' column") else: free_value = int(lines[1].split()[-1]) psutil_value = psutil.virtual_memory().available self.assertAlmostEqual( free_value, psutil_value, delta=MEMORY_TOLERANCE, msg='%s %s \n%s' % (free_value, psutil_value, out)) def test_warnings_on_misses(self): # Emulate a case where /proc/meminfo provides few info. # psutil is supposed to set the missing fields to 0 and # raise a warning. def open_mock(name, *args, **kwargs): if name == '/proc/meminfo': return io.BytesIO(textwrap.dedent("""\ Active(anon): 6145416 kB Active(file): 2950064 kB Inactive(anon): 574764 kB Inactive(file): 1567648 kB MemAvailable: -1 kB MemFree: 2057400 kB MemTotal: 16325648 kB SReclaimable: 346648 kB """).encode()) else: return orig_open(name, *args, **kwargs) orig_open = open patch_point = 'builtins.open' if PY3 else '__builtin__.open' with mock.patch(patch_point, create=True, side_effect=open_mock) as m: with warnings.catch_warnings(record=True) as ws: warnings.simplefilter("always") ret = psutil.virtual_memory() assert m.called self.assertEqual(len(ws), 1) w = ws[0] assert w.filename.endswith('psutil/_pslinux.py') self.assertIn( "memory stats couldn't be determined", str(w.message)) self.assertIn("cached", str(w.message)) self.assertIn("shared", str(w.message)) self.assertIn("active", str(w.message)) self.assertIn("inactive", str(w.message)) self.assertIn("buffers", str(w.message)) self.assertIn("available", str(w.message)) self.assertEqual(ret.cached, 0) self.assertEqual(ret.active, 0) self.assertEqual(ret.inactive, 0) self.assertEqual(ret.shared, 0) self.assertEqual(ret.buffers, 0) self.assertEqual(ret.available, 0) def test_avail_old_percent(self): # Make sure that our calculation of avail mem for old kernels # is off by max 10%. from psutil._pslinux import calculate_avail_vmem from psutil._pslinux import open_binary mems = {} with open_binary('/proc/meminfo') as f: for line in f: fields = line.split() mems[fields[0]] = int(fields[1]) * 1024 a = calculate_avail_vmem(mems) if b'MemAvailable:' in mems: b = mems[b'MemAvailable:'] diff_percent = abs(a - b) / a * 100 self.assertLess(diff_percent, 10) def test_avail_old_comes_from_kernel(self): # Make sure "MemAvailable:" coluimn is used instead of relying # on our internal algorithm to calculate avail mem. def open_mock(name, *args, **kwargs): if name == "/proc/meminfo": return io.BytesIO(textwrap.dedent("""\ Active: 9444728 kB Active(anon): 6145416 kB Active(file): 2950064 kB Buffers: 287952 kB Cached: 4818144 kB Inactive(file): 1578132 kB Inactive(anon): 574764 kB Inactive(file): 1567648 kB MemAvailable: 6574984 kB MemFree: 2057400 kB MemTotal: 16325648 kB Shmem: 577588 kB SReclaimable: 346648 kB """).encode()) else: return orig_open(name, *args, **kwargs) orig_open = open patch_point = 'builtins.open' if PY3 else '__builtin__.open' with mock.patch(patch_point, create=True, side_effect=open_mock) as m: with warnings.catch_warnings(record=True) as ws: ret = psutil.virtual_memory() assert m.called self.assertEqual(ret.available, 6574984 * 1024) w = ws[0] self.assertIn( "inactive memory stats couldn't be determined", str(w.message)) def test_avail_old_missing_fields(self): # Remove Active(file), Inactive(file) and SReclaimable # from /proc/meminfo and make sure the fallback is used # (free + cached), def open_mock(name, *args, **kwargs): if name == "/proc/meminfo": return io.BytesIO(textwrap.dedent("""\ Active: 9444728 kB Active(anon): 6145416 kB Buffers: 287952 kB Cached: 4818144 kB Inactive(file): 1578132 kB Inactive(anon): 574764 kB MemFree: 2057400 kB MemTotal: 16325648 kB Shmem: 577588 kB """).encode()) else: return orig_open(name, *args, **kwargs) orig_open = open patch_point = 'builtins.open' if PY3 else '__builtin__.open' with mock.patch(patch_point, create=True, side_effect=open_mock) as m: with warnings.catch_warnings(record=True) as ws: ret = psutil.virtual_memory() assert m.called self.assertEqual(ret.available, 2057400 * 1024 + 4818144 * 1024) w = ws[0] self.assertIn( "inactive memory stats couldn't be determined", str(w.message)) def test_avail_old_missing_zoneinfo(self): # Remove /proc/zoneinfo file. Make sure fallback is used # (free + cached). def open_mock(name, *args, **kwargs): if name == "/proc/meminfo": return io.BytesIO(textwrap.dedent("""\ Active: 9444728 kB Active(anon): 6145416 kB Active(file): 2950064 kB Buffers: 287952 kB Cached: 4818144 kB Inactive(file): 1578132 kB Inactive(anon): 574764 kB Inactive(file): 1567648 kB MemFree: 2057400 kB MemTotal: 16325648 kB Shmem: 577588 kB SReclaimable: 346648 kB """).encode()) elif name == "/proc/zoneinfo": raise IOError(errno.ENOENT, 'no such file or directory') else: return orig_open(name, *args, **kwargs) orig_open = open patch_point = 'builtins.open' if PY3 else '__builtin__.open' with mock.patch(patch_point, create=True, side_effect=open_mock) as m: with warnings.catch_warnings(record=True) as ws: ret = psutil.virtual_memory() assert m.called self.assertEqual(ret.available, 2057400 * 1024 + 4818144 * 1024) w = ws[0] self.assertIn( "inactive memory stats couldn't be determined", str(w.message)) # ===================================================================== # --- system swap memory # ===================================================================== @unittest.skipIf(not LINUX, "LINUX only") class TestSystemSwapMemory(unittest.TestCase): @staticmethod def meminfo_has_swap_info(): """Return True if /proc/meminfo provides swap metrics.""" with open("/proc/meminfo") as f: data = f.read() return 'SwapTotal:' in data and 'SwapFree:' in data def test_total(self): free_value = free_swap().total psutil_value = psutil.swap_memory().total return self.assertAlmostEqual( free_value, psutil_value, delta=MEMORY_TOLERANCE) @retry_before_failing() def test_used(self): free_value = free_swap().used psutil_value = psutil.swap_memory().used return self.assertAlmostEqual( free_value, psutil_value, delta=MEMORY_TOLERANCE) @retry_before_failing() def test_free(self): free_value = free_swap().free psutil_value = psutil.swap_memory().free return self.assertAlmostEqual( free_value, psutil_value, delta=MEMORY_TOLERANCE) def test_missing_sin_sout(self): with mock.patch('psutil._pslinux.open', create=True) as m: with warnings.catch_warnings(record=True) as ws: warnings.simplefilter("always") ret = psutil.swap_memory() assert m.called self.assertEqual(len(ws), 1) w = ws[0] assert w.filename.endswith('psutil/_pslinux.py') self.assertIn( "'sin' and 'sout' swap memory stats couldn't " "be determined", str(w.message)) self.assertEqual(ret.sin, 0) self.assertEqual(ret.sout, 0) def test_no_vmstat_mocked(self): # see https://github.com/giampaolo/psutil/issues/722 def open_mock(name, *args, **kwargs): if name == "/proc/vmstat": raise IOError(errno.ENOENT, 'no such file or directory') else: return orig_open(name, *args, **kwargs) orig_open = open patch_point = 'builtins.open' if PY3 else '__builtin__.open' with mock.patch(patch_point, create=True, side_effect=open_mock) as m: with warnings.catch_warnings(record=True) as ws: warnings.simplefilter("always") ret = psutil.swap_memory() assert m.called self.assertEqual(len(ws), 1) w = ws[0] assert w.filename.endswith('psutil/_pslinux.py') self.assertIn( "'sin' and 'sout' swap memory stats couldn't " "be determined and were set to 0", str(w.message)) self.assertEqual(ret.sin, 0) self.assertEqual(ret.sout, 0) def test_meminfo_against_sysinfo(self): # Make sure the content of /proc/meminfo about swap memory # matches sysinfo() syscall, see: # https://github.com/giampaolo/psutil/issues/1015 if not self.meminfo_has_swap_info(): return unittest.skip("/proc/meminfo has no swap metrics") with mock.patch('psutil._pslinux.cext.linux_sysinfo') as m: swap = psutil.swap_memory() assert not m.called import psutil._psutil_linux as cext _, _, _, _, total, free, unit_multiplier = cext.linux_sysinfo() total *= unit_multiplier free *= unit_multiplier self.assertEqual(swap.total, total) self.assertEqual(swap.free, free) def test_emulate_meminfo_has_no_metrics(self): # Emulate a case where /proc/meminfo provides no swap metrics # in which case sysinfo() syscall is supposed to be used # as a fallback. def open_mock(name, *args, **kwargs): if name == "/proc/meminfo": return io.BytesIO(b"") else: return orig_open(name, *args, **kwargs) orig_open = open patch_point = 'builtins.open' if PY3 else '__builtin__.open' with mock.patch(patch_point, create=True, side_effect=open_mock) as m: psutil.swap_memory() assert m.called # ===================================================================== # --- system CPU # ===================================================================== @unittest.skipIf(not LINUX, "LINUX only") class TestSystemCPU(unittest.TestCase): @unittest.skipIf(TRAVIS, "unknown failure on travis") def test_cpu_times(self): fields = psutil.cpu_times()._fields kernel_ver = re.findall(r'\d+\.\d+\.\d+', os.uname()[2])[0] kernel_ver_info = tuple(map(int, kernel_ver.split('.'))) if kernel_ver_info >= (2, 6, 11): self.assertIn('steal', fields) else: self.assertNotIn('steal', fields) if kernel_ver_info >= (2, 6, 24): self.assertIn('guest', fields) else: self.assertNotIn('guest', fields) if kernel_ver_info >= (3, 2, 0): self.assertIn('guest_nice', fields) else: self.assertNotIn('guest_nice', fields) @unittest.skipIf(not os.path.exists("/sys/devices/system/cpu/online"), "/sys/devices/system/cpu/online does not exist") def test_cpu_count_logical_w_sysdev_cpu_online(self): with open("/sys/devices/system/cpu/online") as f: value = f.read().strip() if "-" in str(value): value = int(value.split('-')[1]) + 1 self.assertEqual(psutil.cpu_count(), value) @unittest.skipIf(not os.path.exists("/sys/devices/system/cpu"), "/sys/devices/system/cpu does not exist") def test_cpu_count_logical_w_sysdev_cpu_num(self): ls = os.listdir("/sys/devices/system/cpu") count = len([x for x in ls if re.search(r"cpu\d+$", x) is not None]) self.assertEqual(psutil.cpu_count(), count) @unittest.skipIf(not which("nproc"), "nproc utility not available") def test_cpu_count_logical_w_nproc(self): num = int(sh("nproc --all")) self.assertEqual(psutil.cpu_count(logical=True), num) @unittest.skipIf(not which("lscpu"), "lscpu utility not available") def test_cpu_count_logical_w_lscpu(self): out = sh("lscpu -p") num = len([x for x in out.split('\n') if not x.startswith('#')]) self.assertEqual(psutil.cpu_count(logical=True), num) def test_cpu_count_logical_mocked(self): import psutil._pslinux original = psutil._pslinux.cpu_count_logical() # Here we want to mock os.sysconf("SC_NPROCESSORS_ONLN") in # order to cause the parsing of /proc/cpuinfo and /proc/stat. with mock.patch( 'psutil._pslinux.os.sysconf', side_effect=ValueError) as m: self.assertEqual(psutil._pslinux.cpu_count_logical(), original) assert m.called # Let's have open() return emtpy data and make sure None is # returned ('cause we mimick os.cpu_count()). with mock.patch('psutil._pslinux.open', create=True) as m: self.assertIsNone(psutil._pslinux.cpu_count_logical()) self.assertEqual(m.call_count, 2) # /proc/stat should be the last one self.assertEqual(m.call_args[0][0], '/proc/stat') # Let's push this a bit further and make sure /proc/cpuinfo # parsing works as expected. with open('/proc/cpuinfo', 'rb') as f: cpuinfo_data = f.read() fake_file = io.BytesIO(cpuinfo_data) with mock.patch('psutil._pslinux.open', return_value=fake_file, create=True) as m: self.assertEqual(psutil._pslinux.cpu_count_logical(), original) # Finally, let's make /proc/cpuinfo return meaningless data; # this way we'll fall back on relying on /proc/stat def open_mock(name, *args, **kwargs): if name.startswith('/proc/cpuinfo'): return io.BytesIO(b"") else: return orig_open(name, *args, **kwargs) orig_open = open patch_point = 'builtins.open' if PY3 else '__builtin__.open' with mock.patch(patch_point, side_effect=open_mock, create=True): self.assertEqual(psutil._pslinux.cpu_count_logical(), original) def test_cpu_count_physical_mocked(self): # Have open() return emtpy data and make sure None is returned # ('cause we want to mimick os.cpu_count()) with mock.patch('psutil._pslinux.open', create=True) as m: self.assertIsNone(psutil._pslinux.cpu_count_physical()) assert m.called @unittest.skipIf(not HAS_CPU_FREQ, "not supported") def test_cpu_freq_no_result(self): with mock.patch("psutil._pslinux.glob.glob", return_value=[]): self.assertIsNone(psutil.cpu_freq()) @unittest.skipIf(TRAVIS, "fails on Travis") @unittest.skipIf(not HAS_CPU_FREQ, "not supported") def test_cpu_freq_use_second_file(self): # https://github.com/giampaolo/psutil/issues/981 def glob_mock(pattern): if pattern.startswith("/sys/devices/system/cpu/cpufreq/policy"): flags.append(None) return [] else: flags.append(None) return orig_glob(pattern) flags = [] orig_glob = glob.glob with mock.patch("psutil._pslinux.glob.glob", side_effect=glob_mock, create=True): assert psutil.cpu_freq() self.assertEqual(len(flags), 2) @unittest.skipIf(not HAS_CPU_FREQ, "not supported") def test_cpu_freq_emulate_data(self): def open_mock(name, *args, **kwargs): if name.endswith('/scaling_cur_freq'): return io.BytesIO(b"500000") elif name.endswith('/scaling_min_freq'): return io.BytesIO(b"600000") elif name.endswith('/scaling_max_freq'): return io.BytesIO(b"700000") else: return orig_open(name, *args, **kwargs) orig_open = open patch_point = 'builtins.open' if PY3 else '__builtin__.open' with mock.patch(patch_point, side_effect=open_mock): with mock.patch( 'glob.glob', return_value=['/sys/devices/system/cpu/cpufreq/policy0']): freq = psutil.cpu_freq() self.assertEqual(freq.current, 500.0) self.assertEqual(freq.min, 600.0) self.assertEqual(freq.max, 700.0) @unittest.skipIf(not HAS_CPU_FREQ, "not supported") def test_cpu_freq_emulate_multi_cpu(self): def open_mock(name, *args, **kwargs): if name.endswith('/scaling_cur_freq'): return io.BytesIO(b"100000") elif name.endswith('/scaling_min_freq'): return io.BytesIO(b"200000") elif name.endswith('/scaling_max_freq'): return io.BytesIO(b"300000") else: return orig_open(name, *args, **kwargs) orig_open = open patch_point = 'builtins.open' if PY3 else '__builtin__.open' policies = ['/sys/devices/system/cpu/cpufreq/policy0', '/sys/devices/system/cpu/cpufreq/policy1', '/sys/devices/system/cpu/cpufreq/policy2'] with mock.patch(patch_point, side_effect=open_mock): with mock.patch('glob.glob', return_value=policies): freq = psutil.cpu_freq() self.assertEqual(freq.current, 100.0) self.assertEqual(freq.min, 200.0) self.assertEqual(freq.max, 300.0) @unittest.skipIf(TRAVIS, "fails on Travis") @unittest.skipIf(not HAS_CPU_FREQ, "not supported") def test_cpu_freq_no_scaling_cur_freq_file(self): # See: https://github.com/giampaolo/psutil/issues/1071 def open_mock(name, *args, **kwargs): if name.endswith('/scaling_cur_freq'): raise IOError(errno.ENOENT, "") elif name.endswith('/cpuinfo_cur_freq'): return io.BytesIO(b"200000") else: return orig_open(name, *args, **kwargs) orig_open = open patch_point = 'builtins.open' if PY3 else '__builtin__.open' policies = ['/sys/devices/system/cpu/cpufreq/policy0', '/sys/devices/system/cpu/cpufreq/policy1', '/sys/devices/system/cpu/cpufreq/policy2'] with mock.patch(patch_point, side_effect=open_mock): with mock.patch('glob.glob', return_value=policies): freq = psutil.cpu_freq() self.assertEqual(freq.current, 200) # Also test that NotImplementedError is raised in case no # current freq file is present. def open_mock(name, *args, **kwargs): if name.endswith('/scaling_cur_freq'): raise IOError(errno.ENOENT, "") elif name.endswith('/cpuinfo_cur_freq'): raise IOError(errno.ENOENT, "") else: return orig_open(name, *args, **kwargs) orig_open = open patch_point = 'builtins.open' if PY3 else '__builtin__.open' with mock.patch(patch_point, side_effect=open_mock): with mock.patch('glob.glob', return_value=policies): self.assertRaises(NotImplementedError, psutil.cpu_freq) # ===================================================================== # --- system CPU stats # ===================================================================== @unittest.skipIf(not LINUX, "LINUX only") class TestSystemCPUStats(unittest.TestCase): @unittest.skipIf(TRAVIS, "fails on Travis") def test_ctx_switches(self): vmstat_value = vmstat("context switches") psutil_value = psutil.cpu_stats().ctx_switches self.assertAlmostEqual(vmstat_value, psutil_value, delta=500) @unittest.skipIf(TRAVIS, "fails on Travis") def test_interrupts(self): vmstat_value = vmstat("interrupts") psutil_value = psutil.cpu_stats().interrupts self.assertAlmostEqual(vmstat_value, psutil_value, delta=500) # ===================================================================== # --- system network # ===================================================================== @unittest.skipIf(not LINUX, "LINUX only") class TestSystemNetwork(unittest.TestCase): def test_net_if_addrs_ips(self): for name, addrs in psutil.net_if_addrs().items(): for addr in addrs: if addr.family == psutil.AF_LINK: self.assertEqual(addr.address, get_mac_address(name)) elif addr.family == socket.AF_INET: self.assertEqual(addr.address, get_ipv4_address(name)) # TODO: test for AF_INET6 family def test_net_if_stats(self): for name, stats in psutil.net_if_stats().items(): try: out = sh("ifconfig %s" % name) except RuntimeError: pass else: # Not always reliable. # self.assertEqual(stats.isup, 'RUNNING' in out, msg=out) self.assertEqual(stats.mtu, int(re.findall(r'(?i)MTU[: ](\d+)', out)[0])) @retry_before_failing() def test_net_io_counters(self): def ifconfig(nic): ret = {} out = sh("ifconfig %s" % name) ret['packets_recv'] = int( re.findall(r'RX packets[: ](\d+)', out)[0]) ret['packets_sent'] = int( re.findall(r'TX packets[: ](\d+)', out)[0]) ret['errin'] = int(re.findall(r'errors[: ](\d+)', out)[0]) ret['errout'] = int(re.findall(r'errors[: ](\d+)', out)[1]) ret['dropin'] = int(re.findall(r'dropped[: ](\d+)', out)[0]) ret['dropout'] = int(re.findall(r'dropped[: ](\d+)', out)[1]) ret['bytes_recv'] = int( re.findall(r'RX (?:packets \d+ +)?bytes[: ](\d+)', out)[0]) ret['bytes_sent'] = int( re.findall(r'TX (?:packets \d+ +)?bytes[: ](\d+)', out)[0]) return ret nio = psutil.net_io_counters(pernic=True, nowrap=False) for name, stats in nio.items(): try: ifconfig_ret = ifconfig(name) except RuntimeError: continue self.assertAlmostEqual( stats.bytes_recv, ifconfig_ret['bytes_recv'], delta=1024 * 5) self.assertAlmostEqual( stats.bytes_sent, ifconfig_ret['bytes_sent'], delta=1024 * 5) self.assertAlmostEqual( stats.packets_recv, ifconfig_ret['packets_recv'], delta=1024) self.assertAlmostEqual( stats.packets_sent, ifconfig_ret['packets_sent'], delta=1024) self.assertAlmostEqual( stats.errin, ifconfig_ret['errin'], delta=10) self.assertAlmostEqual( stats.errout, ifconfig_ret['errout'], delta=10) self.assertAlmostEqual( stats.dropin, ifconfig_ret['dropin'], delta=10) self.assertAlmostEqual( stats.dropout, ifconfig_ret['dropout'], delta=10) @unittest.skipIf(not which('ip'), "'ip' utility not available") @unittest.skipIf(TRAVIS, "skipped on Travis") def test_net_if_names(self): out = sh("ip addr").strip() nics = [x for x in psutil.net_if_addrs().keys() if ':' not in x] found = 0 for line in out.split('\n'): line = line.strip() if re.search(r"^\d+:", line): found += 1 name = line.split(':')[1].strip() self.assertIn(name, nics) self.assertEqual(len(nics), found, msg="%s\n---\n%s" % ( pprint.pformat(nics), out)) @mock.patch('psutil._pslinux.socket.inet_ntop', side_effect=ValueError) @mock.patch('psutil._pslinux.supports_ipv6', return_value=False) def test_net_connections_ipv6_unsupported(self, supports_ipv6, inet_ntop): # see: https://github.com/giampaolo/psutil/issues/623 try: s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) self.addCleanup(s.close) s.bind(("::1", 0)) except socket.error: pass psutil.net_connections(kind='inet6') def test_net_connections_mocked(self): def open_mock(name, *args, **kwargs): if name == '/proc/net/unix': return io.StringIO(textwrap.dedent(u"""\ 0: 00000003 000 000 0001 03 462170 @/tmp/dbus-Qw2hMPIU3n 0: 00000003 000 000 0001 03 35010 @/tmp/dbus-tB2X8h69BQ 0: 00000003 000 000 0001 03 34424 @/tmp/dbus-cHy80Y8O 000000000000000000000000000000000000000000000000000000 """)) else: return orig_open(name, *args, **kwargs) orig_open = open patch_point = 'builtins.open' if PY3 else '__builtin__.open' with mock.patch(patch_point, side_effect=open_mock) as m: psutil.net_connections(kind='unix') assert m.called # ===================================================================== # --- system disk # ===================================================================== @unittest.skipIf(not LINUX, "LINUX only") class TestSystemDisks(unittest.TestCase): @unittest.skipIf(not hasattr(os, 'statvfs'), "os.statvfs() not available") @skip_on_not_implemented() def test_disk_partitions_and_usage(self): # test psutil.disk_usage() and psutil.disk_partitions() # against "df -a" def df(path): out = sh('df -P -B 1 "%s"' % path).strip() lines = out.split('\n') lines.pop(0) line = lines.pop(0) dev, total, used, free = line.split()[:4] if dev == 'none': dev = '' total, used, free = int(total), int(used), int(free) return dev, total, used, free for part in psutil.disk_partitions(all=False): usage = psutil.disk_usage(part.mountpoint) dev, total, used, free = df(part.mountpoint) self.assertEqual(usage.total, total) # 10 MB tollerance if abs(usage.free - free) > 10 * 1024 * 1024: self.fail("psutil=%s, df=%s" % (usage.free, free)) if abs(usage.used - used) > 10 * 1024 * 1024: self.fail("psutil=%s, df=%s" % (usage.used, used)) def test_disk_partitions_mocked(self): # Test that ZFS partitions are returned. with open("/proc/filesystems", "r") as f: data = f.read() if 'zfs' in data: for part in psutil.disk_partitions(): if part.fstype == 'zfs': break else: self.fail("couldn't find any ZFS partition") else: # No ZFS partitions on this system. Let's fake one. fake_file = io.StringIO(u("nodev\tzfs\n")) with mock.patch('psutil._pslinux.open', return_value=fake_file, create=True) as m1: with mock.patch( 'psutil._pslinux.cext.disk_partitions', return_value=[('/dev/sdb3', '/', 'zfs', 'rw')]) as m2: ret = psutil.disk_partitions() assert m1.called assert m2.called assert ret self.assertEqual(ret[0].fstype, 'zfs') def test_disk_io_counters_kernel_2_4_mocked(self): # Tests /proc/diskstats parsing format for 2.4 kernels, see: # https://github.com/giampaolo/psutil/issues/767 def open_mock(name, *args, **kwargs): if name == '/proc/partitions': return io.StringIO(textwrap.dedent(u"""\ major minor #blocks name 8 0 488386584 hda """)) elif name == '/proc/diskstats': return io.StringIO( u(" 3 0 1 hda 2 3 4 5 6 7 8 9 10 11 12")) else: return orig_open(name, *args, **kwargs) orig_open = open patch_point = 'builtins.open' if PY3 else '__builtin__.open' with mock.patch(patch_point, side_effect=open_mock) as m: ret = psutil.disk_io_counters(nowrap=False) assert m.called self.assertEqual(ret.read_count, 1) self.assertEqual(ret.read_merged_count, 2) self.assertEqual(ret.read_bytes, 3 * SECTOR_SIZE) self.assertEqual(ret.read_time, 4) self.assertEqual(ret.write_count, 5) self.assertEqual(ret.write_merged_count, 6) self.assertEqual(ret.write_bytes, 7 * SECTOR_SIZE) self.assertEqual(ret.write_time, 8) self.assertEqual(ret.busy_time, 10) def test_disk_io_counters_kernel_2_6_full_mocked(self): # Tests /proc/diskstats parsing format for 2.6 kernels, # lines reporting all metrics: # https://github.com/giampaolo/psutil/issues/767 def open_mock(name, *args, **kwargs): if name == '/proc/partitions': return io.StringIO(textwrap.dedent(u"""\ major minor #blocks name 8 0 488386584 hda """)) elif name == '/proc/diskstats': return io.StringIO( u(" 3 0 hda 1 2 3 4 5 6 7 8 9 10 11")) else: return orig_open(name, *args, **kwargs) orig_open = open patch_point = 'builtins.open' if PY3 else '__builtin__.open' with mock.patch(patch_point, side_effect=open_mock) as m: ret = psutil.disk_io_counters(nowrap=False) assert m.called self.assertEqual(ret.read_count, 1) self.assertEqual(ret.read_merged_count, 2) self.assertEqual(ret.read_bytes, 3 * SECTOR_SIZE) self.assertEqual(ret.read_time, 4) self.assertEqual(ret.write_count, 5) self.assertEqual(ret.write_merged_count, 6) self.assertEqual(ret.write_bytes, 7 * SECTOR_SIZE) self.assertEqual(ret.write_time, 8) self.assertEqual(ret.busy_time, 10) def test_disk_io_counters_kernel_2_6_limited_mocked(self): # Tests /proc/diskstats parsing format for 2.6 kernels, # where one line of /proc/partitions return a limited # amount of metrics when it bumps into a partition # (instead of a disk). See: # https://github.com/giampaolo/psutil/issues/767 def open_mock(name, *args, **kwargs): if name == '/proc/partitions': return io.StringIO(textwrap.dedent(u"""\ major minor #blocks name 8 0 488386584 hda """)) elif name == '/proc/diskstats': return io.StringIO( u(" 3 1 hda 1 2 3 4")) else: return orig_open(name, *args, **kwargs) orig_open = open patch_point = 'builtins.open' if PY3 else '__builtin__.open' with mock.patch(patch_point, side_effect=open_mock) as m: ret = psutil.disk_io_counters(nowrap=False) assert m.called self.assertEqual(ret.read_count, 1) self.assertEqual(ret.read_bytes, 2 * SECTOR_SIZE) self.assertEqual(ret.write_count, 3) self.assertEqual(ret.write_bytes, 4 * SECTOR_SIZE) self.assertEqual(ret.read_merged_count, 0) self.assertEqual(ret.read_time, 0) self.assertEqual(ret.write_merged_count, 0) self.assertEqual(ret.write_time, 0) self.assertEqual(ret.busy_time, 0) # ===================================================================== # --- misc # ===================================================================== @unittest.skipIf(not LINUX, "LINUX only") class TestMisc(unittest.TestCase): def test_boot_time(self): vmstat_value = vmstat('boot time') psutil_value = psutil.boot_time() self.assertEqual(int(vmstat_value), int(psutil_value)) @mock.patch('psutil.traceback.print_exc') def test_no_procfs_on_import(self, tb): my_procfs = tempfile.mkdtemp() with open(os.path.join(my_procfs, 'stat'), 'w') as f: f.write('cpu 0 0 0 0 0 0 0 0 0 0\n') f.write('cpu0 0 0 0 0 0 0 0 0 0 0\n') f.write('cpu1 0 0 0 0 0 0 0 0 0 0\n') try: orig_open = open def open_mock(name, *args, **kwargs): if name.startswith('/proc'): raise IOError(errno.ENOENT, 'rejecting access for test') return orig_open(name, *args, **kwargs) patch_point = 'builtins.open' if PY3 else '__builtin__.open' with mock.patch(patch_point, side_effect=open_mock): reload_module(psutil) assert tb.called self.assertRaises(IOError, psutil.cpu_times) self.assertRaises(IOError, psutil.cpu_times, percpu=True) self.assertRaises(IOError, psutil.cpu_percent) self.assertRaises(IOError, psutil.cpu_percent, percpu=True) self.assertRaises(IOError, psutil.cpu_times_percent) self.assertRaises( IOError, psutil.cpu_times_percent, percpu=True) psutil.PROCFS_PATH = my_procfs self.assertEqual(psutil.cpu_percent(), 0) self.assertEqual(sum(psutil.cpu_times_percent()), 0) # since we don't know the number of CPUs at import time, # we awkwardly say there are none until the second call per_cpu_percent = psutil.cpu_percent(percpu=True) self.assertEqual(sum(per_cpu_percent), 0) # ditto awkward length per_cpu_times_percent = psutil.cpu_times_percent(percpu=True) self.assertEqual(sum(map(sum, per_cpu_times_percent)), 0) # much user, very busy with open(os.path.join(my_procfs, 'stat'), 'w') as f: f.write('cpu 1 0 0 0 0 0 0 0 0 0\n') f.write('cpu0 1 0 0 0 0 0 0 0 0 0\n') f.write('cpu1 1 0 0 0 0 0 0 0 0 0\n') self.assertNotEqual(psutil.cpu_percent(), 0) self.assertNotEqual( sum(psutil.cpu_percent(percpu=True)), 0) self.assertNotEqual(sum(psutil.cpu_times_percent()), 0) self.assertNotEqual( sum(map(sum, psutil.cpu_times_percent(percpu=True))), 0) finally: shutil.rmtree(my_procfs) reload_module(psutil) self.assertEqual(psutil.PROCFS_PATH, '/proc') def test_boot_time_mocked(self): with mock.patch('psutil._pslinux.open', create=True) as m: self.assertRaises( RuntimeError, psutil._pslinux.boot_time) assert m.called def test_users_mocked(self): # Make sure ':0' and ':0.0' (returned by C ext) are converted # to 'localhost'. with mock.patch('psutil._pslinux.cext.users', return_value=[('giampaolo', 'pts/2', ':0', 1436573184.0, True, 2)]) as m: self.assertEqual(psutil.users()[0].host, 'localhost') assert m.called with mock.patch('psutil._pslinux.cext.users', return_value=[('giampaolo', 'pts/2', ':0.0', 1436573184.0, True, 2)]) as m: self.assertEqual(psutil.users()[0].host, 'localhost') assert m.called # ...otherwise it should be returned as-is with mock.patch('psutil._pslinux.cext.users', return_value=[('giampaolo', 'pts/2', 'foo', 1436573184.0, True, 2)]) as m: self.assertEqual(psutil.users()[0].host, 'foo') assert m.called def test_procfs_path(self): tdir = tempfile.mkdtemp() try: psutil.PROCFS_PATH = tdir self.assertRaises(IOError, psutil.virtual_memory) self.assertRaises(IOError, psutil.cpu_times) self.assertRaises(IOError, psutil.cpu_times, percpu=True) self.assertRaises(IOError, psutil.boot_time) # self.assertRaises(IOError, psutil.pids) self.assertRaises(IOError, psutil.net_connections) self.assertRaises(IOError, psutil.net_io_counters) self.assertRaises(IOError, psutil.net_if_stats) self.assertRaises(IOError, psutil.disk_io_counters) self.assertRaises(IOError, psutil.disk_partitions) self.assertRaises(psutil.NoSuchProcess, psutil.Process) finally: psutil.PROCFS_PATH = "/proc" os.rmdir(tdir) def test_sector_size_mock(self): # Test SECTOR_SIZE fallback in case 'hw_sector_size' file # does not exist. def open_mock(name, *args, **kwargs): if PY3 and isinstance(name, bytes): name = name.decode() if "hw_sector_size" in name: flag.append(None) raise IOError(errno.ENOENT, '') else: return orig_open(name, *args, **kwargs) flag = [] orig_open = open patch_point = 'builtins.open' if PY3 else '__builtin__.open' with mock.patch(patch_point, side_effect=open_mock): psutil.disk_io_counters() assert flag def test_issue_687(self): # In case of thread ID: # - pid_exists() is supposed to return False # - Process(tid) is supposed to work # - pids() should not return the TID # See: https://github.com/giampaolo/psutil/issues/687 t = ThreadTask() t.start() try: p = psutil.Process() tid = p.threads()[1].id assert not psutil.pid_exists(tid), tid pt = psutil.Process(tid) pt.as_dict() self.assertNotIn(tid, psutil.pids()) finally: t.stop() def test_pid_exists_no_proc_status(self): # Internally pid_exists relies on /proc/{pid}/status. # Emulate a case where this file is empty in which case # psutil is supposed to fall back on using pids(). def open_mock(name, *args, **kwargs): if name == "/proc/%s/status" % os.getpid(): return io.StringIO(u("")) else: return orig_open(name, *args, **kwargs) orig_open = open patch_point = 'builtins.open' if PY3 else '__builtin__.open' with mock.patch(patch_point, side_effect=open_mock): assert psutil.pid_exists(os.getpid()) # ===================================================================== # --- sensors # ===================================================================== @unittest.skipIf(not LINUX, "LINUX only") @unittest.skipIf(not HAS_BATTERY, "no battery") class TestSensorsBattery(unittest.TestCase): @unittest.skipIf(not which("acpi"), "acpi utility not available") def test_percent(self): out = sh("acpi -b") acpi_value = int(out.split(",")[1].strip().replace('%', '')) psutil_value = psutil.sensors_battery().percent self.assertAlmostEqual(acpi_value, psutil_value, delta=1) @unittest.skipIf(not which("acpi"), "acpi utility not available") def test_power_plugged(self): out = sh("acpi -b") if 'unknown' in out.lower(): return unittest.skip("acpi output not reliable") if 'discharging at zero rate' in out: plugged = True else: plugged = "Charging" in out.split('\n')[0] self.assertEqual(psutil.sensors_battery().power_plugged, plugged) def test_emulate_power_plugged(self): # Pretend the AC power cable is connected. def open_mock(name, *args, **kwargs): if name.endswith("AC0/online") or name.endswith("AC/online"): return io.BytesIO(b"1") else: return orig_open(name, *args, **kwargs) orig_open = open patch_point = 'builtins.open' if PY3 else '__builtin__.open' with mock.patch(patch_point, side_effect=open_mock) as m: self.assertEqual(psutil.sensors_battery().power_plugged, True) self.assertEqual( psutil.sensors_battery().secsleft, psutil.POWER_TIME_UNLIMITED) assert m.called def test_emulate_power_plugged_2(self): # Same as above but pretend /AC0/online does not exist in which # case code relies on /status file. def open_mock(name, *args, **kwargs): if name.endswith("AC0/online") or name.endswith("AC/online"): raise IOError(errno.ENOENT, "") elif name.endswith("/status"): return io.StringIO(u("charging")) else: return orig_open(name, *args, **kwargs) orig_open = open patch_point = 'builtins.open' if PY3 else '__builtin__.open' with mock.patch(patch_point, side_effect=open_mock) as m: self.assertEqual(psutil.sensors_battery().power_plugged, True) assert m.called def test_emulate_power_not_plugged(self): # Pretend the AC power cable is not connected. def open_mock(name, *args, **kwargs): if name.endswith("AC0/online") or name.endswith("AC/online"): return io.BytesIO(b"0") else: return orig_open(name, *args, **kwargs) orig_open = open patch_point = 'builtins.open' if PY3 else '__builtin__.open' with mock.patch(patch_point, side_effect=open_mock) as m: self.assertEqual(psutil.sensors_battery().power_plugged, False) assert m.called def test_emulate_power_not_plugged_2(self): # Same as above but pretend /AC0/online does not exist in which # case code relies on /status file. def open_mock(name, *args, **kwargs): if name.endswith("AC0/online") or name.endswith("AC/online"): raise IOError(errno.ENOENT, "") elif name.endswith("/status"): return io.StringIO(u("discharging")) else: return orig_open(name, *args, **kwargs) orig_open = open patch_point = 'builtins.open' if PY3 else '__builtin__.open' with mock.patch(patch_point, side_effect=open_mock) as m: self.assertEqual(psutil.sensors_battery().power_plugged, False) assert m.called def test_emulate_power_undetermined(self): # Pretend we can't know whether the AC power cable not # connected (assert fallback to False). def open_mock(name, *args, **kwargs): if name.startswith("/sys/class/power_supply/AC0/online") or \ name.startswith("/sys/class/power_supply/AC/online"): raise IOError(errno.ENOENT, "") elif name.startswith("/sys/class/power_supply/BAT0/status"): return io.BytesIO(b"???") else: return orig_open(name, *args, **kwargs) orig_open = open patch_point = 'builtins.open' if PY3 else '__builtin__.open' with mock.patch(patch_point, side_effect=open_mock) as m: self.assertIsNone(psutil.sensors_battery().power_plugged) assert m.called def test_emulate_no_base_files(self): # Emulate a case where base metrics files are not present, # in which case we're supposed to get None. def open_mock(name, *args, **kwargs): if name.startswith("/sys/class/power_supply/BAT0/energy_now") or \ name.startswith("/sys/class/power_supply/BAT0/charge_now"): raise IOError(errno.ENOENT, "") else: return orig_open(name, *args, **kwargs) orig_open = open patch_point = 'builtins.open' if PY3 else '__builtin__.open' with mock.patch(patch_point, side_effect=open_mock) as m: self.assertIsNone(psutil.sensors_battery()) assert m.called def test_emulate_energy_full_0(self): # Emulate a case where energy_full files returns 0. def open_mock(name, *args, **kwargs): if name.startswith("/sys/class/power_supply/BAT0/energy_full"): return io.BytesIO(b"0") else: return orig_open(name, *args, **kwargs) orig_open = open patch_point = 'builtins.open' if PY3 else '__builtin__.open' with mock.patch(patch_point, side_effect=open_mock) as m: self.assertEqual(psutil.sensors_battery().percent, 0) assert m.called def test_emulate_energy_full_not_avail(self): # Emulate a case where energy_full file does not exist. # Expected fallback on /capacity. def open_mock(name, *args, **kwargs): energy_full = "/sys/class/power_supply/BAT0/energy_full" charge_full = "/sys/class/power_supply/BAT0/charge_full" if name.startswith(energy_full) or name.startswith(charge_full): raise IOError(errno.ENOENT, "") elif name.startswith("/sys/class/power_supply/BAT0/capacity"): return io.BytesIO(b"88") else: return orig_open(name, *args, **kwargs) orig_open = open patch_point = 'builtins.open' if PY3 else '__builtin__.open' with mock.patch(patch_point, side_effect=open_mock) as m: self.assertEqual(psutil.sensors_battery().percent, 88) assert m.called def test_emulate_no_ac0_online(self): # Emulate a case where /AC0/online file does not exist. def path_exists_mock(name): if name.startswith("/sys/class/power_supply/AC0/online"): return False else: return orig_path_exists(name) orig_path_exists = os.path.exists with mock.patch("psutil._pslinux.os.path.exists", side_effect=path_exists_mock) as m: psutil.sensors_battery() assert m.called def test_emulate_no_power(self): # Emulate a case where /AC0/online file nor /BAT0/status exist. def open_mock(name, *args, **kwargs): if name.startswith("/sys/class/power_supply/AC/online") or \ name.startswith("/sys/class/power_supply/AC0/online") or \ name.startswith("/sys/class/power_supply/BAT0/status"): raise IOError(errno.ENOENT, "") else: return orig_open(name, *args, **kwargs) orig_open = open patch_point = 'builtins.open' if PY3 else '__builtin__.open' with mock.patch(patch_point, side_effect=open_mock) as m: self.assertIsNone(psutil.sensors_battery().power_plugged) assert m.called @unittest.skipIf(not LINUX, "LINUX only") class TestSensorsTemperatures(unittest.TestCase): @unittest.skipIf(TRAVIS, "unreliable on TRAVIS") def test_emulate_eio_error(self): def open_mock(name, *args, **kwargs): if name.endswith("_input"): raise OSError(errno.EIO, "") else: return orig_open(name, *args, **kwargs) orig_open = open patch_point = 'builtins.open' if PY3 else '__builtin__.open' with mock.patch(patch_point, side_effect=open_mock) as m: with warnings.catch_warnings(record=True) as ws: self.assertEqual(psutil.sensors_temperatures(), {}) assert m.called self.assertIn("ignoring", str(ws[0].message)) def test_emulate_data(self): def open_mock(name, *args, **kwargs): if name.endswith('/name'): return io.StringIO(u("name")) elif name.endswith('/temp1_label'): return io.StringIO(u("label")) elif name.endswith('/temp1_input'): return io.BytesIO(b"30000") elif name.endswith('/temp1_max'): return io.BytesIO(b"40000") elif name.endswith('/temp1_crit'): return io.BytesIO(b"50000") else: return orig_open(name, *args, **kwargs) orig_open = open patch_point = 'builtins.open' if PY3 else '__builtin__.open' with mock.patch(patch_point, side_effect=open_mock): with mock.patch('glob.glob', return_value=['/sys/class/hwmon/hwmon0/temp1']): temp = psutil.sensors_temperatures()['name'][0] self.assertEqual(temp.label, 'label') self.assertEqual(temp.current, 30.0) self.assertEqual(temp.high, 40.0) self.assertEqual(temp.critical, 50.0) @unittest.skipIf(not LINUX, "LINUX only") class TestSensorsFans(unittest.TestCase): def test_emulate_data(self): def open_mock(name, *args, **kwargs): if name.endswith('/name'): return io.StringIO(u("name")) elif name.endswith('/fan1_label'): return io.StringIO(u("label")) elif name.endswith('/fan1_input'): return io.StringIO(u("2000")) else: return orig_open(name, *args, **kwargs) orig_open = open patch_point = 'builtins.open' if PY3 else '__builtin__.open' with mock.patch(patch_point, side_effect=open_mock): with mock.patch('glob.glob', return_value=['/sys/class/hwmon/hwmon2/fan1']): fan = psutil.sensors_fans()['name'][0] self.assertEqual(fan.label, 'label') self.assertEqual(fan.current, 2000) # ===================================================================== # --- test process # ===================================================================== @unittest.skipIf(not LINUX, "LINUX only") class TestProcess(unittest.TestCase): def setUp(self): safe_rmpath(TESTFN) tearDown = setUp def test_memory_full_info(self): src = textwrap.dedent(""" import time with open("%s", "w") as f: time.sleep(10) """ % TESTFN) sproc = pyrun(src) self.addCleanup(reap_children) call_until(lambda: os.listdir('.'), "'%s' not in ret" % TESTFN) p = psutil.Process(sproc.pid) time.sleep(.1) mem = p.memory_full_info() maps = p.memory_maps(grouped=False) self.assertAlmostEqual( mem.uss, sum([x.private_dirty + x.private_clean for x in maps]), delta=4096) self.assertAlmostEqual( mem.pss, sum([x.pss for x in maps]), delta=4096) self.assertAlmostEqual( mem.swap, sum([x.swap for x in maps]), delta=4096) # On PYPY file descriptors are not closed fast enough. @unittest.skipIf(PYPY, "unreliable on PYPY") def test_open_files_mode(self): def get_test_file(): p = psutil.Process() giveup_at = time.time() + 2 while True: for file in p.open_files(): if file.path == os.path.abspath(TESTFN): return file elif time.time() > giveup_at: break raise RuntimeError("timeout looking for test file") # with open(TESTFN, "w"): self.assertEqual(get_test_file().mode, "w") with open(TESTFN, "r"): self.assertEqual(get_test_file().mode, "r") with open(TESTFN, "a"): self.assertEqual(get_test_file().mode, "a") # with open(TESTFN, "r+"): self.assertEqual(get_test_file().mode, "r+") with open(TESTFN, "w+"): self.assertEqual(get_test_file().mode, "r+") with open(TESTFN, "a+"): self.assertEqual(get_test_file().mode, "a+") # note: "x" bit is not supported if PY3: safe_rmpath(TESTFN) with open(TESTFN, "x"): self.assertEqual(get_test_file().mode, "w") safe_rmpath(TESTFN) with open(TESTFN, "x+"): self.assertEqual(get_test_file().mode, "r+") def test_open_files_file_gone(self): # simulates a file which gets deleted during open_files() # execution p = psutil.Process() files = p.open_files() with tempfile.NamedTemporaryFile(): # give the kernel some time to see the new file call_until(p.open_files, "len(ret) != %i" % len(files)) with mock.patch('psutil._pslinux.os.readlink', side_effect=OSError(errno.ENOENT, "")) as m: files = p.open_files() assert not files assert m.called # also simulate the case where os.readlink() returns EINVAL # in which case psutil is supposed to 'continue' with mock.patch('psutil._pslinux.os.readlink', side_effect=OSError(errno.EINVAL, "")) as m: self.assertEqual(p.open_files(), []) assert m.called def test_open_files_fd_gone(self): # Simulate a case where /proc/{pid}/fdinfo/{fd} disappears # while iterating through fds. # https://travis-ci.org/giampaolo/psutil/jobs/225694530 p = psutil.Process() files = p.open_files() with tempfile.NamedTemporaryFile(): # give the kernel some time to see the new file call_until(p.open_files, "len(ret) != %i" % len(files)) patch_point = 'builtins.open' if PY3 else '__builtin__.open' with mock.patch(patch_point, side_effect=IOError(errno.ENOENT, "")) as m: files = p.open_files() assert not files assert m.called # --- mocked tests def test_terminal_mocked(self): with mock.patch('psutil._pslinux._psposix.get_terminal_map', return_value={}) as m: self.assertIsNone(psutil._pslinux.Process(os.getpid()).terminal()) assert m.called # TODO: re-enable this test. # def test_num_ctx_switches_mocked(self): # with mock.patch('psutil._pslinux.open', create=True) as m: # self.assertRaises( # NotImplementedError, # psutil._pslinux.Process(os.getpid()).num_ctx_switches) # assert m.called def test_cmdline_mocked(self): # see: https://github.com/giampaolo/psutil/issues/639 p = psutil.Process() fake_file = io.StringIO(u('foo\x00bar\x00')) with mock.patch('psutil._pslinux.open', return_value=fake_file, create=True) as m: self.assertEqual(p.cmdline(), ['foo', 'bar']) assert m.called fake_file = io.StringIO(u('foo\x00bar\x00\x00')) with mock.patch('psutil._pslinux.open', return_value=fake_file, create=True) as m: self.assertEqual(p.cmdline(), ['foo', 'bar', '']) assert m.called def test_cmdline_spaces_mocked(self): # see: https://github.com/giampaolo/psutil/issues/1179 p = psutil.Process() fake_file = io.StringIO(u('foo bar ')) with mock.patch('psutil._pslinux.open', return_value=fake_file, create=True) as m: self.assertEqual(p.cmdline(), ['foo', 'bar']) assert m.called fake_file = io.StringIO(u('foo bar ')) with mock.patch('psutil._pslinux.open', return_value=fake_file, create=True) as m: self.assertEqual(p.cmdline(), ['foo', 'bar', '']) assert m.called def test_readlink_path_deleted_mocked(self): with mock.patch('psutil._pslinux.os.readlink', return_value='/home/foo (deleted)'): self.assertEqual(psutil.Process().exe(), "/home/foo") self.assertEqual(psutil.Process().cwd(), "/home/foo") def test_threads_mocked(self): # Test the case where os.listdir() returns a file (thread) # which no longer exists by the time we open() it (race # condition). threads() is supposed to ignore that instead # of raising NSP. def open_mock(name, *args, **kwargs): if name.startswith('/proc/%s/task' % os.getpid()): raise IOError(errno.ENOENT, "") else: return orig_open(name, *args, **kwargs) orig_open = open patch_point = 'builtins.open' if PY3 else '__builtin__.open' with mock.patch(patch_point, side_effect=open_mock) as m: ret = psutil.Process().threads() assert m.called self.assertEqual(ret, []) # ...but if it bumps into something != ENOENT we want an # exception. def open_mock(name, *args, **kwargs): if name.startswith('/proc/%s/task' % os.getpid()): raise IOError(errno.EPERM, "") else: return orig_open(name, *args, **kwargs) with mock.patch(patch_point, side_effect=open_mock): self.assertRaises(psutil.AccessDenied, psutil.Process().threads) def test_exe_mocked(self): with mock.patch('psutil._pslinux.readlink', side_effect=OSError(errno.ENOENT, "")) as m1: with mock.patch('psutil.Process.cmdline', side_effect=psutil.AccessDenied(0, "")) as m2: # No such file error; might be raised also if /proc/pid/exe # path actually exists for system processes with low pids # (about 0-20). In this case psutil is supposed to return # an empty string. ret = psutil.Process().exe() assert m1.called assert m2.called self.assertEqual(ret, "") # ...but if /proc/pid no longer exist we're supposed to treat # it as an alias for zombie process with mock.patch('psutil._pslinux.os.path.lexists', return_value=False): self.assertRaises( psutil.ZombieProcess, psutil.Process().exe) def test_issue_1014(self): # Emulates a case where smaps file does not exist. In this case # wrap_exception decorator should not raise NoSuchProcess. def open_mock(name, *args, **kwargs): if name.startswith('/proc/%s/smaps' % os.getpid()): raise IOError(errno.ENOENT, "") else: return orig_open(name, *args, **kwargs) orig_open = open patch_point = 'builtins.open' if PY3 else '__builtin__.open' with mock.patch(patch_point, side_effect=open_mock) as m: p = psutil.Process() with self.assertRaises(IOError) as err: p.memory_maps() self.assertEqual(err.exception.errno, errno.ENOENT) assert m.called @unittest.skipIf(not HAS_RLIMIT, "not supported") def test_rlimit_zombie(self): # Emulate a case where rlimit() raises ENOSYS, which may # happen in case of zombie process: # https://travis-ci.org/giampaolo/psutil/jobs/51368273 with mock.patch("psutil._pslinux.cext.linux_prlimit", side_effect=OSError(errno.ENOSYS, "")) as m: p = psutil.Process() p.name() with self.assertRaises(psutil.ZombieProcess) as exc: p.rlimit(psutil.RLIMIT_NOFILE) assert m.called self.assertEqual(exc.exception.pid, p.pid) self.assertEqual(exc.exception.name, p.name()) def test_cwd_zombie(self): with mock.patch("psutil._pslinux.os.readlink", side_effect=OSError(errno.ENOENT, "")) as m: p = psutil.Process() p.name() with self.assertRaises(psutil.ZombieProcess) as exc: p.cwd() assert m.called self.assertEqual(exc.exception.pid, p.pid) self.assertEqual(exc.exception.name, p.name()) def test_stat_file_parsing(self): from psutil._pslinux import CLOCK_TICKS def open_mock(name, *args, **kwargs): if name.startswith('/proc/%s/stat' % os.getpid()): args = [ "0", # pid "(cat)", # name "Z", # status "1", # ppid "0", # pgrp "0", # session "0", # tty "0", # tpgid "0", # flags "0", # minflt "0", # cminflt "0", # majflt "0", # cmajflt "2", # utime "3", # stime "4", # cutime "5", # cstime "0", # priority "0", # nice "0", # num_threads "0", # itrealvalue "6", # starttime "0", # vsize "0", # rss "0", # rsslim "0", # startcode "0", # endcode "0", # startstack "0", # kstkesp "0", # kstkeip "0", # signal "0", # blocked "0", # sigignore "0", # sigcatch "0", # wchan "0", # nswap "0", # cnswap "0", # exit_signal "6", # processor ] return io.BytesIO(" ".join(args).encode()) else: return orig_open(name, *args, **kwargs) orig_open = open patch_point = 'builtins.open' if PY3 else '__builtin__.open' with mock.patch(patch_point, side_effect=open_mock): p = psutil.Process() self.assertEqual(p.name(), 'cat') self.assertEqual(p.status(), psutil.STATUS_ZOMBIE) self.assertEqual(p.ppid(), 1) self.assertEqual( p.create_time(), 6 / CLOCK_TICKS + psutil.boot_time()) cpu = p.cpu_times() self.assertEqual(cpu.user, 2 / CLOCK_TICKS) self.assertEqual(cpu.system, 3 / CLOCK_TICKS) self.assertEqual(cpu.children_user, 4 / CLOCK_TICKS) self.assertEqual(cpu.children_system, 5 / CLOCK_TICKS) self.assertEqual(p.cpu_num(), 6) def test_status_file_parsing(self): def open_mock(name, *args, **kwargs): if name.startswith('/proc/%s/status' % os.getpid()): return io.BytesIO(textwrap.dedent("""\ Uid:\t1000\t1001\t1002\t1003 Gid:\t1004\t1005\t1006\t1007 Threads:\t66 Cpus_allowed:\tf Cpus_allowed_list:\t0-7 voluntary_ctxt_switches:\t12 nonvoluntary_ctxt_switches:\t13""").encode()) else: return orig_open(name, *args, **kwargs) orig_open = open patch_point = 'builtins.open' if PY3 else '__builtin__.open' with mock.patch(patch_point, side_effect=open_mock): p = psutil.Process() self.assertEqual(p.num_ctx_switches().voluntary, 12) self.assertEqual(p.num_ctx_switches().involuntary, 13) self.assertEqual(p.num_threads(), 66) uids = p.uids() self.assertEqual(uids.real, 1000) self.assertEqual(uids.effective, 1001) self.assertEqual(uids.saved, 1002) gids = p.gids() self.assertEqual(gids.real, 1004) self.assertEqual(gids.effective, 1005) self.assertEqual(gids.saved, 1006) self.assertEqual(p._proc._get_eligible_cpus(), list(range(0, 8))) @unittest.skipIf(not LINUX, "LINUX only") class TestProcessAgainstStatus(unittest.TestCase): """/proc/pid/stat and /proc/pid/status have many values in common. Whenever possible, psutil uses /proc/pid/stat (it's faster). For all those cases we check that the value found in /proc/pid/stat (by psutil) matches the one found in /proc/pid/status. """ @classmethod def setUpClass(cls): cls.proc = psutil.Process() def read_status_file(self, linestart): with psutil._psplatform.open_text( '/proc/%s/status' % self.proc.pid) as f: for line in f: line = line.strip() if line.startswith(linestart): value = line.partition('\t')[2] try: return int(value) except ValueError: return value raise ValueError("can't find %r" % linestart) def test_name(self): value = self.read_status_file("Name:") self.assertEqual(self.proc.name(), value) def test_status(self): value = self.read_status_file("State:") value = value[value.find('(') + 1:value.rfind(')')] value = value.replace(' ', '-') self.assertEqual(self.proc.status(), value) def test_ppid(self): value = self.read_status_file("PPid:") self.assertEqual(self.proc.ppid(), value) def test_num_threads(self): value = self.read_status_file("Threads:") self.assertEqual(self.proc.num_threads(), value) def test_uids(self): value = self.read_status_file("Uid:") value = tuple(map(int, value.split()[1:4])) self.assertEqual(self.proc.uids(), value) def test_gids(self): value = self.read_status_file("Gid:") value = tuple(map(int, value.split()[1:4])) self.assertEqual(self.proc.gids(), value) @retry_before_failing() def test_num_ctx_switches(self): value = self.read_status_file("voluntary_ctxt_switches:") self.assertEqual(self.proc.num_ctx_switches().voluntary, value) value = self.read_status_file("nonvoluntary_ctxt_switches:") self.assertEqual(self.proc.num_ctx_switches().involuntary, value) def test_cpu_affinity(self): value = self.read_status_file("Cpus_allowed_list:") if '-' in str(value): min_, max_ = map(int, value.split('-')) self.assertEqual( self.proc.cpu_affinity(), list(range(min_, max_ + 1))) def test_cpu_affinity_eligible_cpus(self): value = self.read_status_file("Cpus_allowed_list:") with mock.patch("psutil._pslinux.per_cpu_times") as m: self.proc._proc._get_eligible_cpus() if '-' in str(value): assert not m.called else: assert m.called # ===================================================================== # --- test utils # ===================================================================== @unittest.skipIf(not LINUX, "LINUX only") class TestUtils(unittest.TestCase): def test_open_text(self): with psutil._psplatform.open_text(__file__) as f: self.assertEqual(f.mode, 'rt') def test_open_binary(self): with psutil._psplatform.open_binary(__file__) as f: self.assertEqual(f.mode, 'rb') def test_readlink(self): with mock.patch("os.readlink", return_value="foo (deleted)") as m: self.assertEqual(psutil._psplatform.readlink("bar"), "foo") assert m.called def test_cat(self): fname = os.path.abspath(TESTFN) with open(fname, "wt") as f: f.write("foo ") self.assertEqual(psutil._psplatform.cat(TESTFN, binary=False), "foo") self.assertEqual(psutil._psplatform.cat(TESTFN, binary=True), b"foo") self.assertEqual( psutil._psplatform.cat(TESTFN + '??', fallback="bar"), "bar") if __name__ == '__main__': run_test_module_by_name(__file__) PK!%% test_osx.pynu[ # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """OSX specific tests.""" import os import re import time import psutil from psutil import OSX from psutil.tests import create_zombie_proc from psutil.tests import get_test_subprocess from psutil.tests import HAS_BATTERY from psutil.tests import MEMORY_TOLERANCE from psutil.tests import reap_children from psutil.tests import retry_before_failing from psutil.tests import run_test_module_by_name from psutil.tests import sh from psutil.tests import unittest PAGESIZE = os.sysconf("SC_PAGE_SIZE") if OSX else None def sysctl(cmdline): """Expects a sysctl command with an argument and parse the result returning only the value of interest. """ out = sh(cmdline) result = out.split()[1] try: return int(result) except ValueError: return result def vm_stat(field): """Wrapper around 'vm_stat' cmdline utility.""" out = sh('vm_stat') for line in out.split('\n'): if field in line: break else: raise ValueError("line not found") return int(re.search(r'\d+', line).group(0)) * PAGESIZE # http://code.activestate.com/recipes/578019/ def human2bytes(s): SYMBOLS = { 'customary': ('B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'), } init = s num = "" while s and s[0:1].isdigit() or s[0:1] == '.': num += s[0] s = s[1:] num = float(num) letter = s.strip() for name, sset in SYMBOLS.items(): if letter in sset: break else: if letter == 'k': sset = SYMBOLS['customary'] letter = letter.upper() else: raise ValueError("can't interpret %r" % init) prefix = {sset[0]: 1} for i, s in enumerate(sset[1:]): prefix[s] = 1 << (i + 1) * 10 return int(num * prefix[letter]) @unittest.skipIf(not OSX, "OSX only") class TestProcess(unittest.TestCase): @classmethod def setUpClass(cls): cls.pid = get_test_subprocess().pid @classmethod def tearDownClass(cls): reap_children() def test_process_create_time(self): output = sh("ps -o lstart -p %s" % self.pid) start_ps = output.replace('STARTED', '').strip() hhmmss = start_ps.split(' ')[-2] year = start_ps.split(' ')[-1] start_psutil = psutil.Process(self.pid).create_time() self.assertEqual( hhmmss, time.strftime("%H:%M:%S", time.localtime(start_psutil))) self.assertEqual( year, time.strftime("%Y", time.localtime(start_psutil))) @unittest.skipIf(not OSX, "OSX only") class TestZombieProcessAPIs(unittest.TestCase): @classmethod def setUpClass(cls): zpid = create_zombie_proc() cls.p = psutil.Process(zpid) @classmethod def tearDownClass(cls): reap_children(recursive=True) def test_pidtask_info(self): self.assertEqual(self.p.status(), psutil.STATUS_ZOMBIE) self.p.ppid() self.p.uids() self.p.gids() self.p.terminal() self.p.create_time() def test_exe(self): self.assertRaises(psutil.ZombieProcess, self.p.exe) def test_cmdline(self): self.assertRaises(psutil.ZombieProcess, self.p.cmdline) def test_environ(self): self.assertRaises(psutil.ZombieProcess, self.p.environ) def test_cwd(self): self.assertRaises(psutil.ZombieProcess, self.p.cwd) def test_memory_full_info(self): self.assertRaises(psutil.ZombieProcess, self.p.memory_full_info) def test_cpu_times(self): self.assertRaises(psutil.ZombieProcess, self.p.cpu_times) def test_num_ctx_switches(self): self.assertRaises(psutil.ZombieProcess, self.p.num_ctx_switches) def test_num_threads(self): self.assertRaises(psutil.ZombieProcess, self.p.num_threads) def test_open_files(self): self.assertRaises(psutil.ZombieProcess, self.p.open_files) def test_connections(self): self.assertRaises(psutil.ZombieProcess, self.p.connections) def test_num_fds(self): self.assertRaises(psutil.ZombieProcess, self.p.num_fds) def test_threads(self): self.assertRaises((psutil.ZombieProcess, psutil.AccessDenied), self.p.threads) def test_memory_maps(self): self.assertRaises(psutil.ZombieProcess, self.p.memory_maps) @unittest.skipIf(not OSX, "OSX only") class TestSystemAPIs(unittest.TestCase): # --- disk def test_disks(self): # test psutil.disk_usage() and psutil.disk_partitions() # against "df -a" def df(path): out = sh('df -k "%s"' % path).strip() lines = out.split('\n') lines.pop(0) line = lines.pop(0) dev, total, used, free = line.split()[:4] if dev == 'none': dev = '' total = int(total) * 1024 used = int(used) * 1024 free = int(free) * 1024 return dev, total, used, free for part in psutil.disk_partitions(all=False): usage = psutil.disk_usage(part.mountpoint) dev, total, used, free = df(part.mountpoint) self.assertEqual(part.device, dev) self.assertEqual(usage.total, total) # 10 MB tollerance if abs(usage.free - free) > 10 * 1024 * 1024: self.fail("psutil=%s, df=%s" % usage.free, free) if abs(usage.used - used) > 10 * 1024 * 1024: self.fail("psutil=%s, df=%s" % usage.used, used) # --- cpu def test_cpu_count_logical(self): num = sysctl("sysctl hw.logicalcpu") self.assertEqual(num, psutil.cpu_count(logical=True)) def test_cpu_count_physical(self): num = sysctl("sysctl hw.physicalcpu") self.assertEqual(num, psutil.cpu_count(logical=False)) def test_cpu_freq(self): freq = psutil.cpu_freq() self.assertEqual( freq.current * 1000 * 1000, sysctl("sysctl hw.cpufrequency")) self.assertEqual( freq.min * 1000 * 1000, sysctl("sysctl hw.cpufrequency_min")) self.assertEqual( freq.max * 1000 * 1000, sysctl("sysctl hw.cpufrequency_max")) # --- virtual mem def test_vmem_total(self): sysctl_hwphymem = sysctl('sysctl hw.memsize') self.assertEqual(sysctl_hwphymem, psutil.virtual_memory().total) @retry_before_failing() def test_vmem_free(self): vmstat_val = vm_stat("free") psutil_val = psutil.virtual_memory().free self.assertAlmostEqual(psutil_val, vmstat_val, delta=MEMORY_TOLERANCE) @retry_before_failing() def test_vmem_available(self): vmstat_val = vm_stat("inactive") + vm_stat("free") psutil_val = psutil.virtual_memory().available self.assertAlmostEqual(psutil_val, vmstat_val, delta=MEMORY_TOLERANCE) @retry_before_failing() def test_vmem_active(self): vmstat_val = vm_stat("active") psutil_val = psutil.virtual_memory().active self.assertAlmostEqual(psutil_val, vmstat_val, delta=MEMORY_TOLERANCE) @retry_before_failing() def test_vmem_inactive(self): vmstat_val = vm_stat("inactive") psutil_val = psutil.virtual_memory().inactive self.assertAlmostEqual(psutil_val, vmstat_val, delta=MEMORY_TOLERANCE) @retry_before_failing() def test_vmem_wired(self): vmstat_val = vm_stat("wired") psutil_val = psutil.virtual_memory().wired self.assertAlmostEqual(psutil_val, vmstat_val, delta=MEMORY_TOLERANCE) # --- swap mem @retry_before_failing() def test_swapmem_sin(self): vmstat_val = vm_stat("Pageins") psutil_val = psutil.swap_memory().sin self.assertEqual(psutil_val, vmstat_val) @retry_before_failing() def test_swapmem_sout(self): vmstat_val = vm_stat("Pageout") psutil_val = psutil.swap_memory().sout self.assertEqual(psutil_val, vmstat_val) # Not very reliable. # def test_swapmem_total(self): # out = sh('sysctl vm.swapusage') # out = out.replace('vm.swapusage: ', '') # total, used, free = re.findall('\d+.\d+\w', out) # psutil_smem = psutil.swap_memory() # self.assertEqual(psutil_smem.total, human2bytes(total)) # self.assertEqual(psutil_smem.used, human2bytes(used)) # self.assertEqual(psutil_smem.free, human2bytes(free)) # --- network def test_net_if_stats(self): for name, stats in psutil.net_if_stats().items(): try: out = sh("ifconfig %s" % name) except RuntimeError: pass else: self.assertEqual(stats.isup, 'RUNNING' in out, msg=out) self.assertEqual(stats.mtu, int(re.findall(r'mtu (\d+)', out)[0])) # --- sensors_battery @unittest.skipIf(not HAS_BATTERY, "no battery") def test_sensors_battery(self): out = sh("pmset -g batt") percent = re.search("(\d+)%", out).group(1) drawing_from = re.search("Now drawing from '([^']+)'", out).group(1) power_plugged = drawing_from == "AC Power" psutil_result = psutil.sensors_battery() self.assertEqual(psutil_result.power_plugged, power_plugged) self.assertEqual(psutil_result.percent, int(percent)) if __name__ == '__main__': run_test_module_by_name(__file__) PK! test_sunos.pynu[ # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Sun OS specific tests.""" import os import psutil from psutil import SUNOS from psutil.tests import run_test_module_by_name from psutil.tests import sh from psutil.tests import unittest @unittest.skipIf(not SUNOS, "SUNOS only") class SunOSSpecificTestCase(unittest.TestCase): def test_swap_memory(self): out = sh('env PATH=/usr/sbin:/sbin:%s swap -l' % os.environ['PATH']) lines = out.strip().split('\n')[1:] if not lines: raise ValueError('no swap device(s) configured') total = free = 0 for line in lines: line = line.split() t, f = line[-2:] total += int(int(t) * 512) free += int(int(f) * 512) used = total - free psutil_swap = psutil.swap_memory() self.assertEqual(psutil_swap.total, total) self.assertEqual(psutil_swap.used, used) self.assertEqual(psutil_swap.free, free) def test_cpu_count(self): out = sh("/usr/sbin/psrinfo") self.assertEqual(psutil.cpu_count(), len(out.split('\n'))) if __name__ == '__main__': run_test_module_by_name(__file__) PK!nrXrX/__pycache__/test_contracts.cpython-36.opt-1.pycnu[3 JZ2^@sdZddlZddlZddlZddlZddlZddlZddlmZddl m Z ddl m Z ddl m Z ddl m Z ddl mZdd l mZdd l mZdd l mZdd l mZdd l mZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddlm$Z$ddlm%Z%ddlm&Z&ddlm'Z'ddl Z Gd d!d!e$j(Z)Gd"d#d#e$j(Z*Gd$d%d%e$j(Z+Gd&d'd'e$j(Z,e-d(kre e.dS))zContracts tests. These tests mainly check API sanity in terms of returned types and APIs availability. Some of these are duplicates of tests test_system.py and test_process.py N)closing)AIX)BSD)FREEBSD)LINUX)NETBSD)OPENBSD)OSX)POSIX)SUNOS)WINDOWS)callable)long)bind_unix_socket)check_connection_ntuple)get_kernel_version)HAS_CONNECTIONS_UNIX) HAS_RLIMIT)HAS_SENSORS_FANS)HAS_SENSORS_TEMPERATURES) is_namedtuple)run_test_module_by_name) safe_rmpath)skip_on_access_denied)TESTFN)unittest)unix_socket_path)VALID_PROC_STATUSES)warnc@seZdZdZddZddZddZdd Zd d Zd d Z ddZ ddZ ddZ ddZ ddZddZddZddZddZd d!Zd"d#Zd$d%Zd&d'Zd(d)Zd*d+Zd,d-Zd.S)/TestAvailabilityzQMake sure code reflects what doc promises in terms of APIs availability. cCs$tp tp t}|jttjd|dS)N cpu_affinity)rr r assertEqualhasattrpsutilProcess)selfhasitr'&/usr/lib64/python3.6/test_contracts.pytest_cpu_affinity<s z"TestAvailability.test_cpu_affinitycCs(|jttdt|jttdtdS)NZwin_service_iterZwin_service_get)r!r"r#r )r%r'r'r(test_win_service@sz!TestAvailability.test_win_servicecCs|jttdtptptdS)NZ PROCFS_PATH)r!r"r#rr r)r%r'r'r(test_PROCFS_PATHDs z!TestAvailability.test_PROCFS_PATHcCsj|j}|ttdt|ttdt|ttdt|ttdt|ttdt|ttdtdS)NZABOVE_NORMAL_PRIORITY_CLASSZBELOW_NORMAL_PRIORITY_CLASSZHIGH_PRIORITY_CLASSZIDLE_PRIORITY_CLASSZNORMAL_PRIORITY_CLASSZREALTIME_PRIORITY_CLASS)r!r"r#r )r%aer'r'r(test_win_priorityHsz"TestAvailability.test_win_prioritycCsJ|j}|ttdt|ttdt|ttdt|ttdtdS)NZIOPRIO_CLASS_NONEZIOPRIO_CLASS_RTZIOPRIO_CLASS_BEZIOPRIO_CLASS_IDLE)r!r"r#r)r%r,r'r'r(test_linux_ioprioQs z"TestAvailability.test_linux_iopriocCsH|j}totdk}|ttjd||ttd||ttd||ttd||ttd||ttd ||ttd ||ttd ||ttd ||ttd ||ttd||ttd||ttd|totdk}|ttd||ttd||ttd||ttd||ttd|dS)N$rlimitZ RLIM_INFINITYZ RLIMIT_ASZ RLIMIT_COREZ RLIMIT_CPUZ RLIMIT_DATAZ RLIMIT_FSIZEZ RLIMIT_LOCKSZRLIMIT_MEMLOCK RLIMIT_NOFILEZ RLIMIT_NPROCZ RLIMIT_RSSZ RLIMIT_STACKrZRLIMIT_MSGQUEUEZ RLIMIT_NICEZ RLIMIT_RTPRIOZ RLIMIT_RTTIMEZRLIMIT_SIGPENDING)r/r0r1)r4r)r!rrr"r#r$)r%r,r&r'r'r(test_linux_rlimitXs*z"TestAvailability.test_linux_rlimitcCs:totjjdptjjd}|jttd|p2tp2tdS)Nz/sys/devices/system/cpu/cpufreqz$/sys/devices/system/cpu/cpu0/cpufreqZcpu_freq) rospathexistsr!r"r#r r )r%linuxr'r'r( test_cpu_freqps  zTestAvailability.test_cpu_freqcCs|jttdtdS)Nsensors_temperatures)r!r"r#r)r%r'r'r(test_sensors_temperaturesvsz*TestAvailability.test_sensors_temperaturescCs|jttdtdS)N sensors_fans)r!r"r#r)r%r'r'r(test_sensors_fansysz"TestAvailability.test_sensors_fanscCs"|jttdtptptptdS)NZsensors_battery)r!r"r#rr rr )r%r'r'r( test_battery|s zTestAvailability.test_batterycCs |jttjdtptptdS)Nenviron)r!r"r#r$rr r )r%r'r'r(test_proc_environsz"TestAvailability.test_proc_environcCs|jttjdtdS)Nuids)r!r"r#r$r )r%r'r'r(test_proc_uidsszTestAvailability.test_proc_uidscCs|jttjdtdS)NrB)r!r"r#r$r )r%r'r'r(test_proc_gidsszTestAvailability.test_proc_gidscCs|jttjdtdS)Nterminal)r!r"r#r$r )r%r'r'r(test_proc_terminalsz#TestAvailability.test_proc_terminalcCs|jttjdtptdS)Nionice)r!r"r#r$rr )r%r'r'r(test_proc_ionicesz!TestAvailability.test_proc_ionicecCs|jttjdtdS)Nr2)r!r"r#r$r)r%r'r'r(test_proc_rlimitsz!TestAvailability.test_proc_rlimitcCs(ttjd}|j|tstrdnddS)N io_countersFT)r"r#r$r!r r )r%r&r'r'r(test_proc_io_counterss z&TestAvailability.test_proc_io_counterscCs|jttjdtdS)Nnum_fds)r!r"r#r$r )r%r'r'r(test_proc_num_fdssz"TestAvailability.test_proc_num_fdscCs|jttjdtdS)N num_handles)r!r"r#r$r )r%r'r'r(test_proc_num_handlessz&TestAvailability.test_proc_num_handlescCs |jttjdtptptdS)Nr )r!r"r#r$rr r)r%r'r'r(test_proc_cpu_affinitysz'TestAvailability.test_proc_cpu_affinitycCs |jttjdtptptdS)Ncpu_num)r!r"r#r$rrr )r%r'r'r(test_proc_cpu_numsz"TestAvailability.test_proc_cpu_numcCs,ttjd}|j|tststr"dnddS)N memory_mapsFT)r"r#r$r!rrr)r%r&r'r'r(test_proc_memory_mapss z&TestAvailability.test_proc_memory_mapsN)__name__ __module__ __qualname____doc__r)r*r+r-r.r5r:r<r>r?rArCrDrFrHrIrKrMrOrPrRrTr'r'r'r(r7s. rc@seZdZddZdS)TestDeprecationsc Csdtjdd}tjjWdQRX|d}|j|jt|jdt |j |jdt |j dS)NT)recordrzmemory_info_ex() is deprecatedzuse memory_info() instead) warningscatch_warningsr#r$memory_info_exassertIsInstancecategory FutureWarningassertInstrmessage)r%Zwswr'r'r(test_memory_info_exs z$TestDeprecations.test_memory_info_exN)rUrVrWrer'r'r'r(rYsrYc@seZdZdZeddZddZddZdd Zd d Z e j e d e j e d eedddZddZddZddZe j e dddZe j e dddZddZdS) TestSystemzCheck the return types of system related APIs. Mainly we want to test we never return unicode on Python 2, see: https://github.com/giampaolo/psutil/issues/1039 cCstj|_dS)N)r#r$proc)clsr'r'r( setUpClassszTestSystem.setUpClasscCs ttdS)N)rr)r%r'r'r(tearDownszTestSystem.tearDowncCs2tj}x$|D]}|j|t|j|dqWdS)Nr)r# cpu_timesr^floatassertGreaterEqual)r%retnr'r'r(test_cpu_timess  zTestSystem.test_cpu_timescCs&x tjddD]}|j|tqWdS)NT)Zperdisk)r#Zdisk_io_countersr^rb)r%kr'r'r(test_io_countersszTestSystem.test_io_counterscCsNxHtjD]<}|j|jt|j|jt|j|jt|j|jtq WdS)N)r#Zdisk_partitionsr^ZdevicerbZ mountpointZfstypeZopts)r%Zdiskr'r'r(test_disk_partitionss zTestSystem.test_disk_partitionsz POSIX onlyzcan't list UNIX sockets)Zonly_ifcCsVtF}tt|.tjdd}x|D]}|j|jtq(WWdQRXWdQRXdS)NZunix)Zkind)rrrr#Znet_connectionsr^Zladdrrb)r%nameZconsconnr'r'r(test_net_connectionss   zTestSystem.test_net_connectionscCsrxltjjD]\\}}|j|txF|D]>}|j|jt|j|jttdf|j|jttdfq(WqWdS)N) r#Z net_if_addrsitemsr^rbZaddressZnetmasktypeZ broadcast)r%ifnameZaddrsaddrr'r'r(test_net_if_addrss   zTestSystem.test_net_if_addrscCs*x$tjjD]\}}|j|tqWdS)N)r#Z net_if_statsrwr^rb)r%ry_r'r'r(test_net_if_statsszTestSystem.test_net_if_statscCs.x(tjddjD]\}}|j|tqWdS)NT)Zpernic)r#Znet_io_countersrwr^rb)r%ryr|r'r'r(test_net_io_countersszTestSystem.test_net_io_countersz not supportedcCsFx@tjjD]0\}}|j|tx|D]}|j|jtq(WqWdS)N)r#r=rwr^rblabel)r%rtunitsunitr'r'r(r>s  zTestSystem.test_sensors_fanscCsFx@tjjD]0\}}|j|tx|D]}|j|jtq(WqWdS)N)r#r;rwr^rbr)r%rtrrr'r'r(r<s  z$TestSystem.test_sensors_temperaturescCsfx`tjD]T}|j|jt|j|jttdf|j|jttdf|j|jt tdfq WdS)N) r#usersr^rtrbrErxhostpidint)r%userr'r'r( test_userss zTestSystem.test_usersN)rUrVrWrX classmethodrirjrprrrsrZskipIfr rrr rvr{r}r~rr>rr<rr'r'r'r(rfs     rfc@s(eZdZdZddZddZddZdd Zd d Zd d Z ddZ ddZ ddZ ddZ ddZddZddZddZddZd d!Zd"d#Zd$d%Zd&d'Zd(d)Zd*d+Zd,d-Zd.d/Zd0d1Zd2d3Zd4d5Zd6d7Zd8d9Zd:d;Z dd?Z"d@dAZ#dBdCZ$dDdEZ%dFdGZ&dHS)ITestFetchAllProcessesz~Test which iterates over all running processes and performs some sanity checks against Process API's returned values. cCsdtr`ddl}ddl}|j}|j}tdd|D|_tdd|D|_tdd|D|_dS)NrcSsg|] }|jqSr')Zpw_uid).0xr'r'r( (sz/TestFetchAllProcesses.setUp..cSsg|] }|jqSr')Zpw_name)rrr'r'r(r)scSsg|] }|jqSr')Zgr_gid)rrr'r'r(r*s) r pwdgrpZgetpwallZgetgrallsetall_uids all_usernamesall_gids)r%rrrgroupsr'r'r(setUp"szTestFetchAllProcesses.setUpcCsd}tdddddddd d d d g }tr6t r6|jd g}x2ttjD]$}|jdrVqF||kr`qF|j|qFWt }g}xtj D]}|j x|D]}|}ydf} i} t ||d} | dk rt | r|d krtjf} n|dkrddi} | | | }n| }|d7}Wn2tk r>d|jjd|} t| Yqtjtjfk r} z0|j| j|j| jr|j| j|jWYdd} ~ Xqtk r>} zdddd}|d||f7}||kr|dt|7}|d7}|dd7}|dtj7}djdd|jD}|d7}|j|PWYdd} ~ XqX|ddgdd ifkrVt ||}|||qWWdQRXqW|r|jd j|dS)!NrZ send_signalZsuspendZresumeZ terminatekillwaitZas_dictparentZchildrenr]oneshotr2r|rSZgroupedFz&%r was skipped because not implementedz.test_ =FzFAIL: test_%s (proc=%sz , ret=%s)z) -z %scss|]}d|VqdS) Nz r')rir'r'r( csz7TestFetchAllProcesses.test_fetch_all..g)rrradddirr#r$ startswithappendobjectZ process_iterrgetattrr r3NotImplementedError __class__rUrZ NoSuchProcessZ AccessDeniedr!rrt Exceptionrepr traceback format_excjoin splitlinesZfail)r%Z valid_procsZexcluded_namesZattrsrtdefaultZfailuresprnargskwargsattrmsgerrsmethr'r'r(test_fetch_all,st             z$TestFetchAllProcesses.test_fetch_allcCs*|j|tx|D]}|j|tqWdS)N)r^listrb)r%rnrgpartr'r'r(cmdlinets  zTestFetchAllProcesses.cmdlinecCsN|j|ttdf|s&|j|dn$trJtjj|rJttdrJttdrJdS)NraccessX_OK) r^rbrxr!r r6r7isfiler")r%rnrgr'r'r(exeys zTestFetchAllProcesses.execCs|j|t|j|ddS)Nr)r^rrm)r%rnrgr'r'r(rs zTestFetchAllProcesses.pidcCs |j|ttf|j|ddS)Nr)r^rrrm)r%rnrgr'r'r(ppidszTestFetchAllProcesses.ppidcCs|j|ttsdS)N)r^rbr)r%rnrgr'r'r(rts zTestFetchAllProcesses.namec Cs^|j|ty|j|dWn*tk rFtr@|jtjkr@nYnXtj dtj |dS)Nrz%Y %m %d %H:%M:%S) r^rlrmAssertionErrorrstatusr#Z STATUS_ZOMBIEtimeZstrftimeZ localtime)r%rnrgr'r'r( create_times z!TestFetchAllProcesses.create_timecCs8x2|D]*}|j|t|j|d|j||jqWdS)Nr)r^rrmrar)r%rnrgZuidr'r'r(rBs   zTestFetchAllProcesses.uidscCsDx>|D]6}|j|tt rt r|j|d|j||jqWdS)Nr)r^rr rrmrar)r%rnrggidr'r'r(gidss     zTestFetchAllProcesses.gidscCs"|j|ttr|j||jdS)N)r^rbr rar)r%rnrgr'r'r(usernames zTestFetchAllProcesses.usernamecCs(|j|t|j|d|j|tdS)N?)r^rbZassertNotEqualrar)r%rnrgr'r'r(rs  zTestFetchAllProcesses.statuscCs6x0|D](}|j|ttf|dkr|j|dqWdS)Nrr)r^rrrm)r%rnrgfieldr'r'r(rJs z!TestFetchAllProcesses.io_counterscCs\trx|D]}|j|tq Wtr@|j|jd|j|jdn|j|d|j|ddS)Nrrr/)rrr/)r r^rrrmZioclassvaluera)r%rnrgrr'r'r(rGs  zTestFetchAllProcesses.ionicecCs|j|t|j|ddS)Nr)r^rrm)r%rnrgr'r'r( num_threadss z!TestFetchAllProcesses.num_threadscCsf|j|txT|D]L}|j|jd|j|jd|j|jdx|D]}|j|ttfqFWqWdS)Nr)r^rrmidZ user_timeZ system_timerrl)r%rnrgtrr'r'r(threadss   zTestFetchAllProcesses.threadscCs*x$|D]}|j|t|j|dqWdS)Nr)r^rlrm)r%rnrgror'r'r(rks  zTestFetchAllProcesses.cpu_timescCs|j|tdS)N)r^rl)r%rnrgr'r'r( cpu_percents z!TestFetchAllProcesses.cpu_percentcCs\|j|ttr|dkrdS|j|dtjdkr@|j|d|j|tt tjdS)Nrrr) r^rrrmr# cpu_countr!rarrange)r%rnrgr'r'r(rQs     zTestFetchAllProcesses.cpu_numcCsx(|D] }|j|ttf|j|dqWtrtt rt|jdkrtxx|jD](}|dkrFt||}|j |j||dqFWnDt r|j|j |j |j|j |j|j|j|j|j|j|jdS)Nrvms)r)r^rrrmr rr_fieldsr assertGreaterr Z peak_wsetZwsetZpeak_paged_poolZ paged_poolZpeak_nonpaged_poolZ nonpaged_poolZ peak_pagefileZpagefile)r%rnrgrrtr'r'r( memory_infos   z!TestFetchAllProcesses.memory_infocCsvtjj}xR|jD]H}t||}|j|ttf|j|d||fd|j |||||fdqWt rr|j|j |j dS)Nr)r) r#Zvirtual_memorytotalrrr^rrrmZassertLessEqualrZpssZuss)r%rnrgrrtrr'r'r(memory_full_infos   z&TestFetchAllProcesses.memory_full_infocCs|j|tx|D]}|j|jt|j|jttrF|j|jdqtr|j|j t|j|j t|j|j t|j |j d|j |j d |j|j dqtr|j rqqWdS) Nrrrrdar+a+r)rrdrrr)r^rfdrr7rbr r!rZpositionmodeflagsrmrarr)r%rnrgfr'r'r( open_filess    z TestFetchAllProcesses.open_filescCs|j|t|j|ddS)Nr)r^rrm)r%rnrgr'r'r(rL(s zTestFetchAllProcesses.num_fdscCs2|jt|tt|x|D] }t|qWdS)N)r!lenrr)r%rnrgrur'r'r( connections,s z!TestFetchAllProcesses.connectionscCsh|rd|j|tytj|}WnDtk rb}z(trD|jtjj krDn|jtj krRWYdd}~XnXdS)N) r^rbr6statOSErrorr errnor#Z _psplatformZACCESS_DENIED_SETENOENT)r%rnrgstrr'r'r(cwd1s   zTestFetchAllProcesses.cwdcCs|j|tdS)N)r^rl)r%rnrgr'r'r(memory_percentAs z$TestFetchAllProcesses.memory_percentcCs|j|tdS)N)r^bool)r%rnrgr'r'r( is_runningEsz TestFetchAllProcesses.is_runningcCsB|j|tttj}x$|D]}|j|t|j||qWdS)N)r^rrr#rrra)r%rnrgZcpusror'r'r(r Hs     z"TestFetchAllProcesses.cpu_affinitycCs |j|ttdf|dk rdS)N)r^rbrx)r%rnrgr'r'r(rEPszTestFetchAllProcesses.terminalcCsx|D]}|j|jt|j|jt|j|jtxR|jD]H}t||}|dkr^|jdsq<|dkrhq<|j|tt f|j |dq.)r^rr rr#ra)r%rnrgZ prioritiesr'r'r(nicems  zTestFetchAllProcesses.nicecCs.x(|D] }|j|ttf|j|dqWdS)Nr)r^rrrm)r%rnrgrr'r'r(num_ctx_switchesvs z&TestFetchAllProcesses.num_ctx_switchescCs@|j|t|jt|d|j|dd|j|dddS)Nr/rrrr)r^tupler!rrm)r%rnrgr'r'r(r2|s zTestFetchAllProcesses.rlimitcCs>|j|tx,|jD] \}}|j|t|j|tqWdS)N)r^dictrwrb)r%rnrgrqvr'r'r(r@s  zTestFetchAllProcesses.environN)'rUrVrWrXrrrrrrrtrrBrrrrJrGrrrkrrQrrrrLrrrrr rErSrNrrr2r@r'r'r'r(rsH H      r__main__)/rXrr6rrrr[ contextlibrr#rrrrrrr r r r Zpsutil._compatr rZ psutil.testsrrrrrrrrrrrrrrrrZTestCaserrYrfrrU__file__r'r'r'r( sX                             x^n PK! DD#__pycache__/test_bsd.cpython-36.pycnu[3 JZcE@sdZddlZddlZddlZddlZddlZddlmZddlmZddlmZddlm Z ddl m Z ddl m Z dd l m Z dd l mZdd l mZdd l mZdd l mZddl mZddl mZerejdZejdkredZqdZndZddZddZeje dGdddejZeje dGdddejZeje dGdddejZeje dGd d!d!ejZe d"kree!dS)#z$Tests specific to all BSD platforms.N)BSD)FREEBSD)NETBSD)OPENBSD)get_test_subprocess) HAS_BATTERY)MEMORY_TOLERANCE) reap_children)retry_before_failing)run_test_module_by_name)sh)unittest)which SC_PAGE_SIZEmuseFc Cshtd|}tr(||jddd}nts0trF||jddd}yt|Stk rb|SXdS)zmExpects a sysctl command with an argument and parse the result returning only the value of interest. zsysctl z: N=)r rfindrrint ValueError)cmdlineresultr /usr/lib64/python3.6/test_bsd.pysysctl+s rcCs@td}x&|jdD]}|j|rPqWtdt|jdS)z+Thin wrapper around 'muse' cmdline utility.r zline not foundr)r split startswithrr)Zfieldoutlinerrrr:s  zBSD onlyc@seZdZdZeddZeddZeje dddZ d d Z eje d  d d dZ eje d  d ddZddZdS)BSDSpecificTestCasez)Generic tests common to all BSD variants.cCstj|_dS)N)rpid)clsrrr setUpClassNszBSDSpecificTestCase.setUpClasscCs tdS)N)r )r#rrr tearDownClassRsz!BSDSpecificTestCase.tearDownClassz -o lstart doesn't work on NETBSDcCsPtd|j}|jddj}tj|jj}tjdtj |}|j ||dS)Nzps -o lstart -p %sZSTARTEDz%a %b %e %H:%M:%S %Y) r r"replacestrippsutilProcessZ create_timetimeZstrftimeZ localtime assertEqual)selfoutputZstart_psZ start_psutilrrrtest_process_create_timeVs  z,BSDSpecificTestCase.test_process_create_timecCsdd}xtjddD]}tj|j}||j\}}}}|j|j||j|j|t|j|d krz|j d|j|ft|j |d kr|j d|j |fqWdS) NcSstd|j}|jd}|jd|jd}|jdd\}}}}|dkrRd}t|d}t|d}t|d}||||fS)Nz df -k "%s"rrZnoner&i)r r(rpopr)pathrlinesr devtotalusedfreerrrdfbs      z*BSDSpecificTestCase.test_disks..dfF)all izpsutil=%s, df=%si(ii(i) r)Zdisk_partitionsZ disk_usageZ mountpointr,Zdevicer5absr7Zfailr6)r-r8partZusager4r5r6r7rrr test_disks_s  zBSDSpecificTestCase.test_disksrzsysctl cmd not availablecCs td}|jtjdd|dS)Nzhw.ncpuT)Zlogical)rr,r) cpu_count)r-systrrrtest_cpu_count_logicalzsz*BSDSpecificTestCase.test_cpu_count_logicalcCstd}|j|tjjdS)Nz hw.physmem)rr,r)virtual_memoryr5)r-numrrrtest_virtual_memory_totalsz-BSDSpecificTestCase.test_virtual_memory_totalcCsxztjjD]j\}}ytd|}Wntk r:YqX|j|jd|k|dd|kr|j|jtt j d|dqWdS)Nz ifconfig %sZRUNNING)msgmtuz mtu (\d+)r) r)Z net_if_statsitemsr RuntimeErrorr,ZisuprErrefindall)r-nameZstatsrrrrtest_net_if_statssz%BSDSpecificTestCase.test_net_if_statsN)__name__ __module__ __qualname____doc__ classmethodr$r%r skipIfrr/r=rr@rCrKrrrrr!Js   r!z FREEBSD onlyc@seZdZeddZeddZeddZddZd d Z d d Z ed dZ eddZ eddZ eddZeddZeddZeddZeddZeje dddZeje ded d!Zeje ded"d#Zeje ded$d%Zeje ded&d'Zeje ded(d)Zeje ded*d+Zd,d-Zd.d/Zd0d1Zd2d3Z d4d5Z!eje" d6d7d8Z#eje" d6d9d:Z$eje"d;dS)?FreeBSDSpecificTestCasecCstj|_dS)N)rr")r#rrrr$sz"FreeBSDSpecificTestCase.setUpClasscCs tdS)N)r )r#rrrr%sz%FreeBSDSpecificTestCase.tearDownClassc Cstd|j}tj|jjdd}|jddd}x||r|j}|j}|dd\}}}} } |j} |jd||f| j|jt | | j | j j ds6|j|d | j q6WdS) Nzprocstat -v %sF)Zgroupedrrz%s-%s[r:) r r"r)r*Z memory_mapsrr1r,ZaddrrZrssr2r) r-rmapsr3r fields_startstopZpermsresmaprrrtest_proc_memory_mapss z-FreeBSDSpecificTestCase.test_proc_memory_mapscCs<td|j}|jtj|jj|jddjddS)Nzprocstat -b %srr)r r"r,r)r*Zexer)r-rrrr test_proc_exesz%FreeBSDSpecificTestCase.test_proc_execCsLtd|j}|jdjtj|jjdj|jddjdddS)Nzprocstat -c %s rrr)r r"r,joinr)r*rr)r-rrrrtest_proc_cmdlinesz)FreeBSDSpecificTestCase.test_proc_cmdlinec Cstd|j}|jddjdd\}}}}}}tj|j}|j} |j} |j| jt ||j| j t ||j| j t ||j| jt ||j| j t ||j| j t |dS)Nzprocstat -s %srrr) r r"rr)r*uidsgidsr,realrZ effectiveZsaved) r-rZeuidZruidZsuidZegidZrgidZsgidprcrdrrrtest_proc_uids_gidss& z+FreeBSDSpecificTestCase.test_proc_uids_gidscCsg}td|j}tj|j}x|jdD]}|jj}d|krtt|jd}|jj }|j |||j dq*d|kr*t|jd }|jj }|j |||j dq*Wt |dkrtddS) Nzprocstat -r %srz voluntary contextrz involuntary contextrz)couldn't find lines match in procstat outr]r])r r"r)r*rlowerr(rZnum_ctx_switchesZ voluntaryr,appendZ involuntarylenrG)r-testedrrfr pstat_value psutil_valuerrrtest_proc_ctx_switchess"        z.FreeBSDSpecificTestCase.test_proc_ctx_switchescCsg}td|j}tj|j}x|jdD]}|jj}d|krtd|jd jdd }|jj }|j |||j dq*d|kr*td|jd jdd }|jj }|j |||j dq*Wt |dkrtd dS)Nzprocstat -r %srz user timez0.r.z system timerz)couldn't find lines match in procstat outr]r]r]r])r r"r)r*rrhr(floatZ cpu_timesuserr,risystemrjrG)r-rkrrfr rlrmrrrtest_proc_cpu_timess"        z+FreeBSDSpecificTestCase.test_proc_cpu_timescCs&tdt}|jtjj|tddS)Nzvm.stats.vm.v_active_count)delta)rPAGESIZEassertAlmostEqualr)rAactiver)r-r?rrrtest_vmem_actives z(FreeBSDSpecificTestCase.test_vmem_activecCs&tdt}|jtjj|tddS)Nzvm.stats.vm.v_inactive_count)rt)rrurvr)rAinactiver)r-r?rrrtest_vmem_inactives z*FreeBSDSpecificTestCase.test_vmem_inactivecCs&tdt}|jtjj|tddS)Nzvm.stats.vm.v_wire_count)rt)rrurvr)rAwiredr)r-r?rrrtest_vmem_wireds z'FreeBSDSpecificTestCase.test_vmem_wiredcCs&tdt}|jtjj|tddS)Nzvm.stats.vm.v_cache_count)rt)rrurvr)rAcachedr)r-r?rrrtest_vmem_cacheds z(FreeBSDSpecificTestCase.test_vmem_cachedcCs&tdt}|jtjj|tddS)Nzvm.stats.vm.v_free_count)rt)rrurvr)rAr7r)r-r?rrrtest_vmem_free s z&FreeBSDSpecificTestCase.test_vmem_freecCs"td}|jtjj|tddS)Nz vfs.bufspace)rt)rrvr)rAbuffersr)r-r?rrrtest_vmem_bufferssz)FreeBSDSpecificTestCase.test_vmem_bufferszmuse not installedcCstd}|jtjj|dS)NZTotal)rr,r)rAr5)r-rBrrrtest_muse_vmem_totalsz,FreeBSDSpecificTestCase.test_muse_vmem_totalcCs"td}|jtjj|tddS)NZActive)rt)rrvr)rArwr)r-rBrrrtest_muse_vmem_activesz-FreeBSDSpecificTestCase.test_muse_vmem_activecCs"td}|jtjj|tddS)NZInactive)rt)rrvr)rAryr)r-rBrrrtest_muse_vmem_inactive#sz/FreeBSDSpecificTestCase.test_muse_vmem_inactivecCs"td}|jtjj|tddS)NZWired)rt)rrvr)rAr{r)r-rBrrrtest_muse_vmem_wired*sz,FreeBSDSpecificTestCase.test_muse_vmem_wiredcCs"td}|jtjj|tddS)NZCache)rt)rrvr)rAr}r)r-rBrrrtest_muse_vmem_cached1sz-FreeBSDSpecificTestCase.test_muse_vmem_cachedcCs"td}|jtjj|tddS)NZFree)rt)rrvr)rAr7r)r-rBrrrtest_muse_vmem_free8sz+FreeBSDSpecificTestCase.test_muse_vmem_freecCs"td}|jtjj|tddS)NZBuffer)rt)rrvr)rArr)r-rBrrrtest_muse_vmem_buffers?sz.FreeBSDSpecificTestCase.test_muse_vmem_bufferscCs|jtjjtddddS)Nzvm.stats.sys.v_swtchi)rt)rvr) cpu_stats ctx_switchesr)r-rrrtest_cpu_stats_ctx_switchesFs z3FreeBSDSpecificTestCase.test_cpu_stats_ctx_switchescCs|jtjjtddddS)Nzvm.stats.sys.v_intri)rt)rvr)r interruptsr)r-rrrtest_cpu_stats_interruptsJs z1FreeBSDSpecificTestCase.test_cpu_stats_interruptscCs|jtjjtddddS)Nzvm.stats.sys.v_softi)rt)rvr)rZsoft_interruptsr)r-rrrtest_cpu_stats_soft_interruptsNs z6FreeBSDSpecificTestCase.test_cpu_stats_soft_interruptscCs|jtjjtddddS)Nzvm.stats.sys.v_syscalli)rt)rvr)rZsyscallsr)r-rrrtest_cpu_stats_syscallsRs z/FreeBSDSpecificTestCase.test_cpu_stats_syscallscCsLtd}||jddd}|d|jd}t|}|j|tjdS)Nzsysctl kern.boottimez sec = ,)rrrr,r) boot_time)r-sZbtimerrrtest_boot_time\s z&FreeBSDSpecificTestCase.test_boot_timez no batterycCsdd}td}tdd|jdD}tj}t|djdd }|d }|j|j||d krt|j|j tj n|j||j |dS) NcSs(t|d\}}t|d\}}d||fS)N<z%d:%02d)divmod)Zsecsmrhrrr secs2hoursgsz@FreeBSDSpecificTestCase.test_sensors_battery..secs2hoursz acpiconf -i 0cSs(g|] }|jdd|jddfqS) rrr])r).0xrrr msz@FreeBSDSpecificTestCase.test_sensors_battery..rzRemaining capacity:%r&zRemaining time:unknown) r dictrr)sensors_batteryrr'r,percentsecsleftZPOWER_TIME_UNLIMITED)r-rrrVZmetricsrZremaining_timerrrtest_sensors_batteryesz,FreeBSDSpecificTestCase.test_sensors_batterycCsl|jtjjtd|jtjjtddktjj}|dkrT|jtddn|j|tdddS)Nzhw.acpi.battery.lifezhw.acpi.aclinerrzhw.acpi.battery.timerr])r,r)rrrZ power_pluggedr)r-rrrr#test_sensors_battery_against_sysctlxs    z;FreeBSDSpecificTestCase.test_sensors_battery_against_sysctlz has batteryc Cs@|jttdtdtdWdQRX|jtjdS)Nzhw.acpi.battery.lifezhw.acpi.battery.timezhw.acpi.acline)Z assertRaisesrGrZ assertIsNoner)r)r-rrrtest_sensors_battery_no_batterys  z7FreeBSDSpecificTestCase.test_sensors_battery_no_batteryN)&rLrMrNrPr$r%r r\r^rargrnrsrxrzr|r~rrr rQMUSE_AVAILABLErrrrrrrrrrrrrrrrrrrrrRsF            rRz OPENBSD onlyc@seZdZddZdS)OpenBSDSpecificTestCasecCs6td}tjj|d}tjjtj}|j||dS)Nz kern.boottimez%a %b %d %H:%M:%S %Y)rdatetimeZstrptimeZ fromtimestampr)rr,)r-rZsys_btZ psutil_btrrrrsz&OpenBSDSpecificTestCase.test_boot_timeN)rLrMrNrrrrrrsrz NETBSD onlyc@s`eZdZeddZddZddZddZd d Zd d Z d dZ ddZ ddZ ddZ dS)NetBSDSpecificTestCasec CsRtdd2}x*|D]"}|j|rt|jddSqWWdQRXtd|dS)Nz /proc/meminforbriz can't find %s)openrrrr)Zlook_forfr rrr parse_meminfos    "z$NetBSDSpecificTestCase.parse_meminfocCs|jtjj|jddS)Nz MemTotal:)r,r)rAr5r)r-rrrtest_vmem_totalsz&NetBSDSpecificTestCase.test_vmem_totalcCs |jtjj|jdtddS)NzMemFree:)rt)rvr)rAr7rr)r-rrrrsz%NetBSDSpecificTestCase.test_vmem_freecCs |jtjj|jdtddS)NzBuffers:)rt)rvr)rArrr)r-rrrrsz(NetBSDSpecificTestCase.test_vmem_bufferscCs |jtjj|jdtddS)Nz MemShared:)rt)rvr)rAZsharedrr)r-rrrtest_vmem_sharedsz'NetBSDSpecificTestCase.test_vmem_sharedcCs |jtjj|jdtddS)Nz SwapTotal:)rt)rvr) swap_memoryr5rr)r-rrrtest_swapmem_totalsz)NetBSDSpecificTestCase.test_swapmem_totalcCs |jtjj|jdtddS)Nz SwapFree:)rt)rvr)rr7rr)r-rrrtest_swapmem_freesz(NetBSDSpecificTestCase.test_swapmem_freecCs"tj}|j|j|j|jdS)N)r)rr,r6r5r7)r-Zsmemrrrtest_swapmem_usedsz(NetBSDSpecificTestCase.test_swapmem_usedc Csbtdd8}x0|D] }|jdrt|jd}PqWtdWdQRX|jtjj|dddS)Nz /proc/statrsintrrzcouldn't find linei)rt) rrrrrrvr)rr)r-rr rrrrrs   z0NetBSDSpecificTestCase.test_cpu_stats_interruptsc Csbtdd8}x0|D] }|jdrt|jd}PqWtdWdQRX|jtjj|dddS)Nz /proc/statrsctxtrzcouldn't find linei)rt) rrrrrrvr)rr)r-rr rrrrrs   z2NetBSDSpecificTestCase.test_cpu_stats_ctx_switchesN)rLrMrN staticmethodrrrrrrrrrrrrrrrs  r__main__)"rOrosrHr+r)rrrrZ psutil.testsrrrr r r r r rsysconfrugetuidrrrrQZTestCaser!rRrrrL__file__rrrr sL                 K   B PK!Zaa,__pycache__/test_system.cpython-36.opt-1.pycnu[3 JZ/@sdZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl m Z ddl mZddl mZddl mZddl mZddl mZdd l mZdd l mZdd l mZdd l mZdd lmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddlm$Z$ddlm%Z%ddlm&Z&ddlm'Z'ddlm(Z(ddlm)Z)ddlm*Z*ddlm+Z+dd lm,Z,dd!lm-Z-Gd"d#d#e-j.Z/e0d$kre(e1dS)%zTests for system APIS.N)AIX)BSD)FREEBSD)LINUX)NETBSD)OPENBSD)OSX)POSIX)SUNOS)WINDOWS)long)APPVEYOR)ASCII_FS)check_net_address)DEVNULL)enum)get_test_subprocess) HAS_BATTERY) HAS_CPU_FREQ)HAS_SENSORS_BATTERY)HAS_SENSORS_FANS)HAS_SENSORS_TEMPERATURES)mock) reap_children)retry_before_failing)run_test_module_by_name) safe_rmpath)TESTFN)TESTFN_UNICODE)TRAVIS)unittestc@sBeZdZdZddZddZddZdd Zd d Zd d Z ddZ e j e dddZddZddZddZddZddZddZdd Zd!d"Zd#d$Zd%d&Zd'd(Zd)d*Zd+d,Zd-d.Zd/d0Zd1d2Zd3d4Zd5d6Z d7d8Z!d9d:Z"d;d<Z#d=d>Z$d?d@Z%dAdBZ&dCdDZ'dEdFZ(dGdHZ)e j e*dIdJdKZ+e j e,o\e-j.j/dL dMe j e0ote1j2dNkdOdPdQZ3dRdSZ4e j e0pe*oe1j5 dTdUdVZ6dWdXZ7e j e8 dYdZd[Z9d\d]Z:e j e; d^d_d`Z d^e j e? dcdddeZ@e j eA d^dfdgZBdNS)hTestSystemAPIszTests for system-related APIs.cCs ttdS)N)rr)selfr##/usr/lib64/python3.6/test_system.pysetUp>szTestSystemAPIs.setUpcCs tdS)N)r)r"r#r#r$tearDownAszTestSystemAPIs.tearDowncCs|jtjddtjDt}|j|jddtjDtj|j}|j|j |j |jddtjDt j dtj tjd|jttjgWdQRXt j dtjtjd*|jtjttjWdQRXWdQRXdS)NcSsg|] }|jqSr#)pid).0xr#r#r$ Esz4TestSystemAPIs.test_process_iter..cSsg|] }|jqSr#)r')r(r)r#r#r$r*GscSsg|] }|jqSr#)r')r(r)r#r#r$r*Kszpsutil.Process) side_effect)assertInosgetpidpsutil process_iterrr'Processkillwait assertNotInrpatchZ NoSuchProcess assertEquallist AccessDenied assertRaises)r"sprocpr#r#r$test_process_iterDs z TestSystemAPIs.test_process_itercCs"x.tjdgdD]}|jt|jjdgqW|jtttjdgdWdQRXtj dtj dddB}x:tjddgdD]&}|j |jd|j |jddqWWdQRXtj dtj dddL}t }x>tjddg|d D](}|j|jd||j |jddqWWdQRXdS) Nr')attrsZfooz$psutil._psplatform.Process.cpu_timesr)r+ cpu_times)r=Zad_value)r/r0r6r7infokeysr9 ValueErrorrr5r8 assertIsNoneassertGreaterEqualobjectassertIs)r"r;mflagr#r#r$test_prcess_iter_w_paramsUs$  z(TestSystemAPIs.test_prcess_iter_w_paramsc sfdd}gt}t}t}dd|||fD}jttj|ddjttj|ddtj}tj|d|d \}}jtj|d j|gjt |d jgx|D]} j t | d qWt d fdd} |j | ||\}}j|jdd|Dtr4j|jjtj nj|jjdj|jgx|D]} j t | d q\Wt d fdd} |j |j | ||\}}jtt|j|j|jgx|D]} jt | d qWdS)Ncsj|jdS)N)appendr')r;)pidsr#r$callbackjsz0TestSystemAPIs.test_wait_procs..callbackcSsg|]}tj|jqSr#)r/r1r')r(r)r#r#r$r*qsz2TestSystemAPIs.test_wait_procs..)timeout)rLg{Gz?)rNrLg? returncodecs<tj|d|d\}}jt|djt|d||fS)NgQ?)rNrLrM)r/ wait_procsr6len)procsrLgonealive)r"r#r$test~s  z,TestSystemAPIs.test_wait_procs..testcSsg|] }|jqSr#)r')r(r)r#r#r$r*scs<tj|d|d\}}jt|djt|d||fS)NgQ?)rNrLrOr)r/rSr6rT)rUrLrVrW)r"r#r$rXs  )rr9rBr/rS TypeErrortime assertLessr6rT assertFalsehasattrr terminater,r'r poprPsignalSIGTERMset assertTrue) r"rLsproc1sproc2sproc3rUtrVrWr;rXr#)rKr"r$test_wait_procsisB       zTestSystemAPIs.test_wait_procscCsNt}t}t}dd|||fD}x|D] }|jq,Wtj|\}}dS)NcSsg|]}tj|jqSr#)r/r1r')r(r)r#r#r$r*sz=TestSystemAPIs.test_wait_procs_no_timeout..)rr_r/rS)r"rerfrgrUr;rVrWr#r#r$test_wait_procs_no_timeouts  z)TestSystemAPIs.test_wait_procs_no_timeoutcCs4tj}|j|t|j|d|j|tjdS)Nr)r/Z boot_timeassertIsInstancefloat assertGreaterr\r[)r"Zbtr#r#r$test_boot_times  zTestSystemAPIs.test_boot_timez POSIX onlycCs"ddl}|jtjd|jdS)Nr SC_PAGE_SIZE)resourcer6r-sysconfZ getpagesize)r"rpr#r#r$ test_PAGESIZEszTestSystemAPIs.test_PAGESIZEcCstj}xt|jD]j}t||}|dkr6|j|ttf|dkr|dksX|jd||f||jkr|jd||j||fqWdS)Npercenttotalrz %r < 0 (%s)z%r > total (total=%s, %s=%s)) r/Zvirtual_memory_fieldsgetattrrkintr failrt)r"memnamevaluer#r#r$test_virtual_memorys   z"TestSystemAPIs.test_virtual_memorycCs&tj}|j|jd|jdkr"ndS) Nrtusedfreerssinsoutr)rtr}r~rsrr)r/Z swap_memoryr6rurt)r"ryr#r#r$test_swap_memorys   zTestSystemAPIs.test_swap_memorycCstt}|jtj|jtj|j}|j|j|jtj|j|jtjd|j tjddtj kdS)NrMrrY) rrdr/ pid_existsr'r1r2r3r]r6rK)r"r:r;r#r#r$test_pid_existss zTestSystemAPIs.test_pid_existsc Csttj}xF|D]>}yWqtk rPtjd|tjkrL|j|YqXqWtt|dt|d}x |D]}|j tj ||dqvWdS)Ng?iip)msg) rr/rKAssertionErrorr[sleeprxrangemaxr]r)r"rKr'r#r#r$test_pid_exists_2s    z TestSystemAPIs.test_pid_exists_2cCsJddtjD}tj}|j|j|j|jt|tt|dS)NcSsg|] }|jqSr#)r')r(r)r#r#r$r*sz,TestSystemAPIs.test_pids..)r/r0rKr6sortrTrc)r"ZplistZpidlistr#r#r$ test_pidsszTestSystemAPIs.test_pidsc Cs&tj}tt_z tjWd|t_XdS)N)sysstdoutrr/rX)r"rr#r#r$ test_tests  zTestSystemAPIs.test_testc Cstj}|j|ttjdd|j|dtjjdrft d}|j }WdQRXd|krft j dtjdd}|j|d|j||dS) NT)percpurMz /proc/cpuinfoz physical idz#cpuinfo doesn't include physical idF)logical) r/ cpu_countr6rTr?rDr-pathexistsopenreadr ZSkipTest)r"rfdZ cpuinfo_dataZphysicalr#r#r$test_cpu_counts      zTestSystemAPIs.test_cpu_countcCsfx`d D]X}tjd|d}|jtjWdQRXtjd|d}|jtjddWdQRXqWdS) NrMrz$psutil._psplatform.cpu_count_logical) return_valuez%psutil._psplatform.cpu_count_physicalF)rrY)rYrN)rr5rCr/r)r"valrGr#r#r$test_cpu_count_nones    z"TestSystemAPIs.test_cpu_count_nonecCs^d}tj}t|x,|D]$}|j|t|j|d||7}qW|j|t|t|dS)Nrg)r/r?sumrkrlrDr6str)r"rttimescp_timer#r#r$test_cpu_timess    zTestSystemAPIs.test_cpu_timescCsDttj}tjdttj}||}|dks@|jd|dS)Ng?g?z difference %s)rr/r?r[rrx)r"t1t2 differencer#r#r$test_cpu_times_time_increases:s    z,TestSystemAPIs.test_cpu_times_time_increasescCsxftjddD]V}d}t|x,|D]$}|j|t|j|d||7}q$W|j|t|t|qW|jttjdddttjdddS)NT)rrgF) r/r?rrkrlrDr6rrT)r"rrtrr#r#r$test_per_cpu_timesCs     z!TestSystemAPIs.test_per_cpu_timescCstjdd}tjd}xtj|krPqWtjdd}x.rM)delta)r/r?_makerruassertAlmostEqualrv)r"baseZper_cpuZ summed_valuesZfieldr#r#r$test_cpu_times_comparisonts   z(TestSystemAPIs.test_cpu_times_comparisoncCsy<|j|t|j|d|j|d|j|dtjWn@tk r|}z$td|tj |tj |fWYdd}~XnXdS)NggY@z %s last=%s new=%sg) rkrlrDZ assertIsNotassertLessEqualr/rrpprintZpformat)r"rsZlast_retZnew_reterrr#r#r$_test_cpu_percent~s   z TestSystemAPIs._test_cpu_percentc Csbtjdd}x.tdD]"}tjdd}|j||||}qW|jttjddWdQRXdS)NgMbP?)intervaldrMrY)r/ cpu_percentrrr9rB)r"lastr)newr#r#r$test_cpu_percents   zTestSystemAPIs.test_cpu_percentc Cstjddd}|jt|tjx>tdD]2}tjddd}x|D]}|j|||qDW|}q,W|jttjdddWdQRXdS)NgMbP?T)rrrrMrY) r/rr6rTrrrr9rB)r"rr)rrsr#r#r$test_per_cpu_percents  z#TestSystemAPIs.test_per_cpu_percentcCs`tjdd}xNtdD]B}tjdd}x|D]}|j|||q,W|jt||||}qWdS)NgMbP?)rr)r/cpu_times_percentrrr)r"rr)rrsr#r#r$test_cpu_times_percents   z%TestSystemAPIs.test_cpu_times_percentcCstjddd}|jt|tjx^tdD]R}tjddd}x:|D]2}x|D]}|j|||qNW|jt|||qDW|}q,WdS)NgMbP?T)rrr)r/rr6rTrrrr)r"rr)rcpursr#r#r$test_per_cpu_times_percents  z)TestSystemAPIs.test_per_cpu_times_percentc CsrtjddddtjddD}tjd|d8x0tjddD] }x|D]}|j|ddqJWq@WWdQRXdS)NT)rcSs*g|]"}|jddtt|jDqS)cSsg|]}dqS)rr#)r(r)r#r#r$r*szQTestSystemAPIs.test_per_cpu_times_percent_negative...)rrrTru)r(r)r#r#r$r*szFTestSystemAPIs.test_per_cpu_times_percent_negative..zpsutil.cpu_times)r)r/rr?rr5r)r"Z zero_timesrrsr#r#r$#test_per_cpu_times_percent_negatives  z2TestSystemAPIs.test_per_cpu_times_percent_negativec Cstjtj}|j|jd ttdrptjtj}d }|j|j|j|j |j |j |d|j |j |j |dt j }|jt}tj|WdQRX|j|jjtjdS) Nrtr}r~rs disk_usagei)r)rtr}r~rsiiP)r/rr-getcwdr6rur^shutilrtrr~r}tempfileZmktempr9OSErrorZ exceptionerrnoENOENT)r"ZusageZ shutil_usageZ toleranceZfnameexcr#r#r$test_disk_usages    zTestSystemAPIs.test_disk_usagec Cs(tr$|jttjtWdQRXdS)N)rr9UnicodeEncodeErrorr/rr)r"r#r#r$test_disk_usage_unicodes z&TestSystemAPIs.test_disk_usage_unicodecCstjddS)N.)r/r)r"r#r#r$test_disk_usage_bytessz$TestSystemAPIs.test_disk_usage_bytescCstjdd}|j||dxj|D]b}|j|jt|j|jt|j|jt|j|jtt rld|jkrlq t srn|jt st r q q Wtjdd}|j||dxtjddD]}t s(yt j|jWnPtk r}z2t rtr|jtjkrw|jtjtjfkrWYdd}~XnXt s(t r(n|j|jt|j|jtqWdd}|t}dd tjddD}|j||tj|dS) NF)all)rZcdromTcSs2tjj|}xtjj|s(tjj|}qW|jS)N)r-rabspathismountdirnamelower)rr#r#r$find_mount_points z=TestSystemAPIs.test_disk_partitions..find_mount_pointcSsg|]}|jjqSr#) mountpointr)r(r)r#r#r$r*sz7TestSystemAPIs.test_disk_partitions..)r/Zdisk_partitionsrdrkZdevicerrZfstypeZoptsr r r rr-statrrrZEIOZEPERMZEACCES__file__r,r)r"lsZdiskrrZmountZmountsr#r#r$test_disk_partitionssH     z#TestSystemAPIs.test_disk_partitionscslfdd}tjdd}||tjdd}j|gx.|D]&}j|j|t|||q>WdS)Ncsj|d|jj|d|jj|d|jj|d|jj|d|jj|d|jj|d|jj|d|jdS) NrrMrRrOr) r6Z bytes_sentZ bytes_recvZ packets_sentZ packets_recvZerrinZerroutZdropinZdropout)nt)r"r#r$ check_ntuplesz9TestSystemAPIs.test_net_io_counters..check_ntupleF)pernicT)r/net_io_countersassertNotEqualrdrkr)r"rretkeyr#)r"r$test_net_io_counterss       z#TestSystemAPIs.test_net_io_countersc CsDtjdid,}|jtjdd|jtjddiWdQRXdS)Nz"psutil._psplatform.net_io_counters)rF)rT)rr5rCr/rr6)r"rGr#r#r$test_net_io_counters_no_nics8s  z+TestSystemAPIs.test_net_io_counters_no_nicsc Cshtj}tj}ttjtjtjg}x|jD]\}}|j |t |j t t|t |x|D]}|j |j t|j |jt |j |jt tdf|j |jt tdf|j|j |tjdkr|j |j tj||jr|j tjkr*tj|j }tj||j|jdfWdQRXnj|j tjkrtj|jdtjtjdtjd}|\} } } } } tj| | | }tj||j| WdQRXxB|j|j|j|jfD]*}|dk r|j tjkrt ||j qW|jr|j!|jqf|jrf|j!|jqfWq0Wt"st#st$r8t%tdrd|j tjtjn,t&rP|j tjtj'nt(rd|j tjddS)NrOrrAF_LINKrM)rOrrY))r/ net_if_addrs net_if_statsrcsocketZAF_INETZAF_INET6ritemsrkrr6rTZfamilyrwaddressZnetmasktypeZ broadcastr,r version_inforIntEnumisup contextlibclosingZbindZ getaddrinfoZ SOCK_STREAMZ AI_PASSIVEZptprrCrrr r^rZ AF_PACKETr )r"nicsZ nic_statsZfamiliesZnicZaddrsaddrsr@ZafZsocktypeprotoZ canonnameZsaZipr#r#r$test_net_if_addrsAsV          z TestSystemAPIs.test_net_if_addrsc Csptrdtjddddfg}nd g}tjd|d8}tjdd}trT|j|jdn|j|jd WdQRXdS) Nem1z06:3d:29rM06-3d-29zpsutil._psplatform.net_if_addrs)rrz06:3d:29:00:00:00z06-3d-29-00-00-00rY)rrYrNNN)r r/rrr5rr6r)r"rrGrr#r#r$ test_net_if_addrs_mac_null_bytes}s z/TestSystemAPIs.test_net_if_addrs_mac_null_byteszunreliable on TRAVISc Cstj}tjtjtjf}xh|jD]\\}}|j|t|\}}}}|j|t|j |||j |||j |d|j |dq"WdS)Nr) r/rZNIC_DUPLEX_FULLZNIC_DUPLEX_HALFZNIC_DUPLEX_UNKNOWNrrkrboolr,rD) r"rZ all_duplexesrzZstatsrZduplexZspeedZmtur#r#r$test_net_if_statss      z TestSystemAPIs.test_net_if_statsz/proc/diskstatsz3/proc/diskstats not available on this linux versionNzunreliable on APPVEYORcsfdd}tjdd}||tjdd}jt|tt|xV|D]N}|||trJ|djrJx|djr|dd }qlWj||jqJWdS) Ncsj|d|jj|d|jj|d|jj|d|jtpNtsƈj|d|jj|d|jt rj|d|j j|d|j j|d |j nt rƈj|d|j x|jD]}qWdS) NrrMrRrOrrrr)r6Z read_countZ write_countZ read_bytesZ write_bytesrrZ read_timeZ write_timerZread_merged_countZwrite_merged_countZ busy_timerru)rrz)r"r#r$rs z:TestSystemAPIs.test_disk_io_counters..check_ntupleF)perdiskTrMrYrYrY) r/disk_io_countersr6rTrcrisdigitr4rA)r"rrrr#)r"r$test_disk_io_counterss     z$TestSystemAPIs.test_disk_io_countersc CsDtjdid,}|jtjdd|jtjddiWdQRXdS)Nz#psutil._psplatform.disk_io_counters)rF)rT)rr5rCr/rr6)r"rGr#r#r$test_disk_io_counters_no_diskss  z-TestSystemAPIs.test_disk_io_counters_no_disksz unreliable on APPVEYOR or TRAVIScCstj}|j|gx|D]}|j|jt|j|jttdf|jdk rb|j|jttdf|j|jt j j |j t st r|j|jqtj|jqWdS)N)r/usersrrkrzrZterminalrhostdatetimeZ fromtimestampZstartedr rrCr'r1)r"ruserr#r#r$ test_userss   zTestSystemAPIs.test_userscCsZtj}|j|jdx>|jD]4}t||}|j|dt r|dkr|j|dqWdS)N ctx_switches interruptssoft_interruptssyscallsr)rrrr)rr)r/Z cpu_statsr6rurvrDrrm)r"Zinfosrzr{r#r#r$test_cpu_statss   zTestSystemAPIs.test_cpu_statsz not suportedcsTfdd}tjdd}tr&| r&dS|tjddgtrPjt|tjdS)Ncshxb|D]Z}j|jdj|j|jx6|jD],}t||}j|ttt fj |dq0WqWdS)Ncurrentminrr)rrr) r6rurrrrvrkrwr rlrD)rrrzr{)r"r#r$check_lss   z.TestSystemAPIs.test_cpu_freq..check_lsT)rF)r/Zcpu_freqrrr6rTr)r"r rr#)r"r$ test_cpu_freqs  zTestSystemAPIs.test_cpu_freqc Cs8ddddddddd g }x"|D]}|jtt|t|d qWtjd kr|jdd tjj krj|jdnd tjj kr|j tj tj tj gjdd|jd|jd|jd|jdnBdtjj ksdtjj kr|jd ndtjj kr|jdn |jdx$|D]}|jtt|d|d qWdS)Nr r rrrrrrr )rposixlinuxZbsdTrMsunossolarisdarwinF)rkrvr/rr-rzremoverplatformrr6rrrcountrF)r"namesrzr#r#r$test_os_constantss.               z TestSystemAPIs.test_os_constantsz not supportedcCstj}x|jD]x\}}|j|txb|D]Z}|j|jt|jdk rV|j|jd|jdk rn|j|jd|j dk r,|j|j dq,WqWdS)Nr) r/sensors_temperaturesrrkrlabelrrDhighcritical)r"tempsrzentriesentryr#r#r$test_sensors_temperatures)s     z(TestSystemAPIs.test_sensors_temperaturesc Csfddgi}tjd|dD}tjdd dd }|j|jd |j|jd |j|jd WdQRXdS)NZcoretemprI@N@Q@z'psutil._psplatform.sensors_temperatures)rT)Z fahrenheitrg^@ga@gc@)rrrr)rr5r/rr6rrr)r"drGrr#r#r$#test_sensors_temperatures_fahreneit7s  z2TestSystemAPIs.test_sensors_temperatures_fahreneitz no batterycCsptj}|j|jd|j|jd|jtjtjfkrF|j|jdn|jtjkr^|j|j |j |j t dS)Nrr) r/Zsensors_batteryrDrsrZsecsleftZPOWER_TIME_UNKNOWNZPOWER_TIME_UNLIMITEDrdZ power_pluggedrkr)r"rr#r#r$test_sensors_batteryCs   z#TestSystemAPIs.test_sensors_batterycCsjtj}x\|jD]P\}}|j|tx:|D]2}|j|jt|j|jttf|j |jdq,WqWdS)Nr) r/Z sensors_fansrrkrrrrwr rD)r"Zfansrzrrr#r#r$test_sensors_fansQs  z TestSystemAPIs.test_sensors_fans)C__name__ __module__ __qualname____doc__r%r&r<rIrirjrnr ZskipIfr rrr|rrrrrrrrrrrrrrrrrrrrrrrrrrrrrr-rrr r/rrrrrrrr rrrr!rrr"rr#r#r#r#r$r!;sh7     !       > <#  %  r!__main__)2r'rrrr-rrrarrrr[r/rrrrrrrr r r Zpsutil._compatr Z psutil.testsr rrrrrrrrrrrrrrrrrrr ZTestCaser!r$rr#r#r#r$sh                               ' PK!&g[*__pycache__/test_misc.cpython-36.opt-1.pycnu[3 JZ@s|dZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl m Z ddl m Z ddl m Z ddlmZddlmZddlmZdd lmZdd lmZdd lmZdd lmZdd lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddlm$Z$ddlm%Z%ddlm&Z&ddlm'Z'ddlm(Z(ddlm)Z)ddlm*Z*dd lm+Z+dd!lm,Z,dd"lm-Z-dd#lm.Z.dd$lm/Z/dd%lm0Z0dd&lm1Z1dd'lm2Z2dd(lm3Z3dd)lm4Z4dd*lm5Z5dd+lm6Z6dd,lm7Z7dd-lm8Z8dd.lm9Z9dd/lm:Z:dd0lm;Z;dd1lmej?d4d5Z@Gd6d7d7e8j=ZAe8jBe6d8e8jBe7oejCjDe2 d9Gd:d;d;e8j=ZEGdd?d?e8j=ZGGd@dAdAe8j=ZHGdBdCdCe8j=ZIGdDdEdEe8j=ZJGdFdGdGe8j=ZKeLdHkrxe0eMdS)Iz Miscellaneous tests. N)LINUX)POSIX)WINDOWS)memoize)memoize_when_activated) supports_ipv6) wrap_numbers)PY3)APPVEYOR) bind_socket)bind_unix_socket) call_until)chdir)create_proc_children_pair)create_sockets)create_zombie_proc)DEVNULL) get_free_port)get_test_subprocess) HAS_BATTERY)HAS_CONNECTIONS_UNIX)HAS_MEMORY_FULL_INFO)HAS_MEMORY_MAPS)HAS_SENSORS_BATTERY)HAS_SENSORS_FANS)HAS_SENSORS_TEMPERATURES)import_module_by_path) is_namedtuple)mock) PYTHON_EXE) reap_children) reload_module)retry)ROOT_DIR)run_test_module_by_name) safe_rmpath) SCRIPTS_DIR)sh)tcp_socketpair)TESTFN)TOX)TRAVIS)unittest)unix_socket_path)unix_socketpair) wait_for_file) wait_for_pidc@seZdZefddZddZefddZefddZefd d Zefd d Z d dZ ddZ ddZ ddZ ddZddZddZddZddZdd Zd!d"Zd#d$Zd%d&Zd'd(Zd)S)*TestMisccCsntj}||}|jd||jd|j||jd||j|j|tjjtjdtjt j d@tj}||}|jd|j||jd||j d|WdQRXtjjtjdtj t j d@tj}||}|jd|j||jd||j d|WdQRXtjjtjdtj t j d4tj}||}|jd|j||j d|WdQRXdS)Nzpsutil.Processzpid=%szname=name) side_effectZzombieZ terminated)psutilProcessassertInpidr2rpatchobject ZombieProcessosgetpid assertNotIn NoSuchProcess AccessDenied)selffuncprrD!/usr/lib64/python3.6/test_misc.pytest_process__repr__Os4       zTestMisc.test_process__repr__cCs|jtddS)N)rA)rFstr)r@rDrDrEtest_process__str__kszTestMisc.test_process__str__cCsN|jttjdd|jttjdddd|jttjdddddS)NiAz7psutil.NoSuchProcess process no longer exists (pid=321)foo)r2zCpsutil.NoSuchProcess process no longer exists (pid=321, name='foo'))msgzpsutil.NoSuchProcess foo) assertEqualreprr4r>)r@rArDrDrEtest_no_such_process__repr__ns z%TestMisc.test_no_such_process__repr__cCsj|jttjdd|jttjdddd|jttjddddd|jttjddd d dS) NiAzEpsutil.ZombieProcess process still exists but it's a zombie (pid=321)rI)r2zQpsutil.ZombieProcess process still exists but it's a zombie (pid=321, name='foo'))r2ppidzYpsutil.ZombieProcess process still exists but it's a zombie (pid=321, name='foo', ppid=1))rJzpsutil.ZombieProcess foo)rKrLr4r:)r@rArDrDrEtest_zombie_process__repr__zs z$TestMisc.test_zombie_process__repr__cCsN|jttjdd|jttjdddd|jttjdddddS)NiAzpsutil.AccessDenied (pid=321)rI)r2z)psutil.AccessDenied (pid=321, name='foo'))rJzpsutil.AccessDenied foo)rKrLr4r?)r@rArDrDrEtest_access_denied__repr__s z#TestMisc.test_access_denied__repr__cCsP|jttjdd|jttjdddd|jttjddddddS) NiAz/psutil.TimeoutExpired timeout after 321 secondso)r7z9psutil.TimeoutExpired timeout after 321 seconds (pid=111)rI)r7r2zEpsutil.TimeoutExpired timeout after 321 seconds (pid=111, name='foo'))rKrLr4ZTimeoutExpired)r@rArDrDrEtest_timeout_expired__repr__s z%TestMisc.test_timeout_expired__repr__cCs>tj}tj}|j||d|_|j|||j|ddS)NrrI)rr)r4r5rKZ_identassertNotEqual)r@p1p2rDrDrEtest_process__eq__s   zTestMisc.test_process__eq__cCs(ttjtjg}|jt|ddS)NrN)setr4r5rKlen)r@srDrDrEtest_process__hash__szTestMisc.test_process__hash__c Cstt}x|D]~}|d krq|jd sy t|Wqtk r|tjkrtt|}|dkr`w|jdk rd |jjkr|j d |YqXqWxtjD]}|j ||qWdS)Ncallableerror namedtupletestslongtestNUM_CPUS BOOT_TIME TOTAL_PHYMEM_Z deprecatedz%r not in psutil.__all__) r\r]r^r_r`rarbrcrd) dirr4 startswith __import__ ImportError__all__getattr__doc__lowerfailr6)r@Z dir_psutilr2ZfunrDrDrE test__all__s&       zTestMisc.test__all__cCs$|jdjddtjDtjdS)N.cSsg|] }t|qSrD)rG).0xrDrDrE sz)TestMisc.test_version..)rKjoinr4 version_info __version__)r@rDrDrE test_versionszTestMisc.test_versioncCs"tj}d|_|jd|jdS)N1rI)r4r5rIr=as_dict)r@rBrDrDrE!test_process_as_dict_no_new_namessz*TestMisc.test_process_as_dict_no_new_namescstfdd}gx:tdD].}|}fif}|j|||jtdqWx.foorN)barrz foo docstring)rN)rN)rrangerKrY cache_clearrl)r@rIrrretZexpectedrD)r~rE test_memoizes.      zTestMisc.test_memoizecsGfddd}|}g|j|j|jtdg|jj|j|j|jtdg|jj|j|j|jtddS)NcseZdZefddZdS)z1TestMisc.test_memoize_when_activated..FoocsjddS)N)r{)r@)r~rDrErIsz5TestMisc.test_memoize_when_activated..Foo.fooN)__name__ __module__ __qualname__rrIrD)r~rDrEFoosrrrN)rIrKrYZcache_activateZcache_deactivate)r@rfrD)r~rEtest_memoize_when_activateds   z$TestMisc.test_memoize_when_activatedcCsddlm}dd}|j|d|ddi|j|d|dd|d d i|j|d |dd|d d i|j|d |dd|d d i|j|d|ddi|j|d|ddi|j|d|ddidS)Nr)parse_environ_blockcSstr |jS|S)N)rupper)rZrDrDrEksz,TestMisc.test_parse_environ_block..kza=1arxz a=1b=2b2za=1b=z a=1b=2c=3zxxxa=1z a=1=b=2za=1b=2)psutil._commonrrK)r@rrrDrDrEtest_parse_environ_blocks     z!TestMisc.test_parse_environ_blockcCs|jtjtrtjd}d|_tjWdQRXtjtjdtjd}WdQRXtjtjdtjd}tjWdQRXtjtjdtjd}tjWdQRXn0|j t  tjtj tj }|j dWdQRXdS) Nzpsutil._common.socketFzpsutil._common.socket.socket)r3z!psutil._common.socket.socket.bind::1r)rr) addCleanuprrrr8Zhas_ipv6socketr]Zgaierror assertRaises ExceptionAF_INET6 SOCK_STREAMZbind)r@rZsockrDrDrEtest_supports_ipv6%s.          zTestMisc.test_supports_ipv6cCsddlm}tjjt}tjdtt j dd|j t||WdQRXtjdtt j dd|j t||WdQRXtjdtt j ddWdQRXtjdddWdQRXdS) Nr) isfile_strictzpsutil._common.os.statrI)r3zpsutil._common.stat.S_ISREGF) return_value)rrr;pathabspath__file__rr8OSErrorerrnoZEPERMrZEACCESEINVAL)r@rZ this_filerDrDrEtest_isfile_strictEs   zTestMisc.test_isfile_strictcsfdd}|tjj|tj|tj|tj|tjdd|tjtrpt j j d rpnt s|tj |tj|tjt j|tjdS)Ncs<tdk rtjtj|tj|}tj|}j||dS)N)jsonloadsdumpspicklerK)rrr)r@rDrEcheckWs   z*TestMisc.test_serialization..checkr)intervalz/proc/diskstats)r4r5ryZvirtual_memoryZ swap_memoryZ cpu_timesZcpu_times_percentnet_io_countersrr;rexistsr disk_io_countersZdisk_partitionsZ disk_usagegetcwdusers)r@rrD)r@rEtest_serializationVs       zTestMisc.test_serializationcCsVtjjtd}tr*tjj| r*|jdSt|}|jt |j |j |j t jdS)Nzsetup.pyzcan't find setup.py)r;rrtr#r+rZskipTestrr SystemExitZsetuprKZ get_versionr4rv)r@Zsetup_pymodulerDrDrEtest_setup_scriptms  zTestMisc.test_setup_scriptcCstjjtjdtjd}tjWdQRXtjjtjdtjdd}tjWdQRXtjjtjdtd$}|jttjWdQRXWdQRXdS)NZ create_time)r3rN) rr8r9r4r5r?r: ValueErrorr)r@methrDrDrEtest_ad_on_process_creationus        z$TestMisc.test_ad_on_process_creationcCsRtjddd:|jt}ttWdQRX|jdt|jj WdQRXdS)Nzpsutil._psplatform.cext.versionz0.0.0)rzversion conflict) rr8rrir!r4r6rG exceptionrm)r@cmrDrDrEtest_sanity_version_checks   z"TestMisc.test_sanity_version_checkN)rrrrLrFrHrMrPrQrSrWr[rorwrzrrrrrrrrrrDrDrDrEr1Ms(   # r1rIza b cc@seZdZddZeZddZddZddZd d Zd d Z d dZ ddZ ddZ ddZ ddZddZddZejej pej dddZdS)TestWrapNumberscCs tjdS)N)rr)r@rDrDrEsetUpszTestWrapNumbers.setUpcCs&dtdddi}|jt|d|dS)Ndisk1disk_io)ntrKr)r@inputrDrDrEtest_first_callszTestWrapNumbers.test_first_callcCs8dtdddi}|jt|d||jt|d|dS)Nrrr)rrKr)r@rrDrDrEtest_input_hasnt_changedsz(TestWrapNumbers.test_input_hasnt_changedcCsdtdddi}|jt|d|dtdddi}|jt|d|dtdddi}|jt|d|dtdddi}|jt|d|dS) Nrrr )rrKr)r@rrDrDrEtest_increase_but_no_wrapsz)TestWrapNumbers.test_increase_but_no_wrapcCsdtdddi}|jt|d|dtdddi}|jt|ddtdddidtdddi}|jt|ddtdddidtdddi}|jt|ddtdddidtdddi}|jt|ddtddd idtdddi}|jt|ddtddd idtd ddi}|jt|ddtd dd idtd ddi}|jt|ddtddd idtd ddi}|jt|ddtddd idS) NrdrrnZr2()rrKr)r@rrDrDrE test_wraps4        zTestWrapNumbers.test_wrapcCstdtdddi}|jt|d|tdddtdddd}|jt|d|dtdddi}|jt|d|dS)Nrrr)rdisk2)rrKr)r@rrDrDrEtest_changing_keyss z"TestWrapNumbers.test_changing_keyscCs.tdddtdddd}|jt|d|tdddtdddd}|jt|dtdddtdddddtdddi}|jt|d|tdddtdddd}|jt|d|tdddtdddd}|jt|d|tdddtdddd}|jt|dtdddtdddddS)Nrr)rrrrrr)rrKr)r@rrDrDrEtest_changing_keys_w_wraps*         z)TestWrapNumbers.test_changing_keys_w_wrapc Csbd'd(d)d*d"}|jt|d#||jt|d#|d+d,d-d.d"}t|d#}|j|d%dd&dS)/N,#RȷrtUrr6$NrrU "r4\)nvme0n1Z nvme0n1p1Z nvme0n1p2Z nvme0n1p3rrri) rrrrrrrrr) rrrrrrrrr) rrrrrrrrr) rrrrrrrrr) rrrrrrrrr) rrrrrrrrr) rrrrrrrrr) rrrrrrrrr)rKr)r@doutrDrDrEtest_real_datas zTestWrapNumbers.test_real_datacCsbdtdddi}t|dtj}|j|dd|i|j|ddii|j|ddiidS)NrrrrrNr)rr cache_inforK)r@rcacherDrDrEtest_cache_first_calls  z%TestWrapNumbers.test_cache_first_callc Csdtdddi}t|ddtdddi}t|dtj}|j|dd|i|j|ddddd dd dii|j|ddiidS) NrrrrrrNr)rr)rrN)rr)rrrrK)r@rrrDrDrEtest_cache_call_twices  z%TestWrapNumbers.test_cache_call_twicec sdtdddi}t|ddtdddi}t|dtj}j|dd|ij|ddd dddddiij|dddtdgiifdd }dtdddi}t|dtj}j|dd|i|dtddd i}t|dtj}j|dd|i|dtddd i}t|dtj}j|dd|ij|dddddddd iij|dddtdgiidS)NrrrrrrNrc sJtj}j|ddddddd diij|dddtd giidS) NrNrrrrr)rr)rrN)rr)rr)rrrKrX)r)r@rDrEassert_4s   z0TestWrapNumbers.test_cache_wrap..assert_rrr)rr)rrN)rr)rr)rr)rrN)rr)rr)rrrrKrX)r@rrrrD)r@rEtest_cache_wrap%s:      zTestWrapNumbers.test_cache_wrapc Csdtdddi}t|dtdddtdddd}t|dtj}|j|dd|i|j|ddd dd dd dii|j|ddiidS) Nrrrr)rrrrNr)rr)rrN)rr)rrrrK)r@rrrDrDrEtest_cache_changing_keysUs   z(TestWrapNumbers.test_cache_changing_keyscCs\dtdddi}t|dt|dtjd|jtjiiiftjdtjddS)Nrrrz?!?)rrrrKr)r@rrDrDrEtest_cache_clearbs    z TestWrapNumbers.test_cache_clearzno disks or NICs availablecCstjtjtj}x$|D]}|jd||jd|qWtjjtj}x$|D]}|jd||jd|qVWtjjtj}|j|iiifdS)Nzpsutil.disk_io_counterszpsutil.net_io_counters) r4rrrrr6rr=rK)r@ZcachesrrDrDrEtest_cache_clear_public_apisks      z,TestWrapNumbers.test_cache_clear_public_apisN)rrrrtearDownrrrrrrrrrrrrr,skipIfr4rrrrDrDrDrErs" %  0  rzcan't test on TOXzcan't locate scripts directoryc@seZdZdZeddZed=ddZddZej e d d d Z d d Z ddZ ddZddZej epxeoxej dddZddZddZddZej edddZej e d d!d"Zej e d d#d$Zd%d&Zd'd(Zd)d*Zd+d,Z d-d.Z!ej e" d/d0d1Z#d2d3Z$ej e% d ej edd4d5Z&ej e' d ej edd6d7Z(ej e) d ej e* d8d9d:Z+d;d<Z,dS)> TestScriptsz-Tests for scripts in the "scripts" directory.cOsdtjjt|}t|g}x|D]}|j|q Wyt|f|j}Wn8tk r~}zdt |krlt |SWYdd}~XnX|S)Nz%sr?) r;rrtr&rr{r'strip RuntimeErrorrG)exer|r}cmdargrerrrDrDrE assert_stdouts  zTestScripts.assert_stdoutNc CsRtjjt|}tr"t|ddd}n t|d}||j}WdQRXtj|dS)NZrtutf8)encoding) r;rrtr&r openreadastparse)rr|rsrcrDrDrE assert_syntaxs zTestScripts.assert_syntaxcCsZt|}xLtjtD]>}|jdrdtjj|d|kr|jdtjjt|qWdS)Nz.pyZtest_rzno test defined for %r script) rfr;listdirr&endswithrsplitextrnrt)r@Zmethsr2rDrDrE test_coverages  zTestScripts.test_coveragez POSIX onlycCsTxNtjtD]@}|jdr tjjt|}tjtj|tj@s |j d|q WdS)Nz.pyz%r is not executable) r;rr&rrrtstatS_IXUSRST_MODErn)r@r2rrDrDrEtest_executables  zTestScripts.test_executablecCs|jddS)Nz disk_usage.py)r )r@rDrDrEtest_disk_usageszTestScripts.test_disk_usagecCs|jddS)Nzfree.py)r )r@rDrDrE test_freeszTestScripts.test_freecCs|jddS)Nz meminfo.py)r )r@rDrDrE test_meminfoszTestScripts.test_meminfocCs|jdttjdS)Nz procinfo.py)r rGr;r<)r@rDrDrE test_procinfoszTestScripts.test_procinfoz unreliable on APPVEYOR or TRAVIScCs|jddS)Nzwho.py)r )r@rDrDrEtest_whoszTestScripts.test_whocCs|jddS)Nzps.py)r )r@rDrDrEtest_psszTestScripts.test_pscCs|jddS)Nz pstree.py)r )r@rDrDrE test_pstreeszTestScripts.test_pstreecCs|jddS)Nz netstat.py)r )r@rDrDrE test_netstatszTestScripts.test_netstatzunreliable on TRAVIScCs|jddS)Nz ifconfig.py)r )r@rDrDrE test_ifconfigszTestScripts.test_ifconfigz not supportedcCs|jdttjdS)Nzpmap.py)r rGr;r<)r@rDrDrE test_pmapszTestScripts.test_pmapcCs|jdtddS)Nz procsmem.py)stderr)r r)r@rDrDrE test_procsmemszTestScripts.test_procsmemcCs|jddS)Nz killall.py)r)r@rDrDrE test_killallszTestScripts.test_killallcCs|jddS)Nz nettop.py)r)r@rDrDrE test_nettopszTestScripts.test_nettopcCs|jddS)Nztop.py)r)r@rDrDrEtest_topszTestScripts.test_topcCs|jddS)Nziotop.py)r)r@rDrDrE test_iotopszTestScripts.test_iotopcCs,|jdtjj}|jttj|dS)Nzpidof.py)r r4r5r2r6rGr;r<)r@outputrDrDrE test_pidofszTestScripts.test_pidofz WINDOWS onlycCs|jddS)Nzwinservices.py)r )r@rDrDrEtest_winservicesszTestScripts.test_winservicescCs|jddS)Nzcpu_distribution.py)r)r@rDrDrEtest_cpu_distributionsz!TestScripts.test_cpu_distributioncCs|jddS)Nztemperatures.py)r )r@rDrDrEtest_temperaturesszTestScripts.test_temperaturescCs|jddS)Nzfans.py)r )r@rDrDrE test_fansszTestScripts.test_fansz no batterycCs|jddS)Nz battery.py)r )r@rDrDrE test_batteryszTestScripts.test_batterycCs|jddS)Nz sensors.py)r )r@rDrDrE test_sensorsszTestScripts.test_sensors)N)-rrrrl staticmethodr rrr,rrrrrrrr r+r4rr r!r"r#r$rr%rr'r(r)r*r+r-rr.r/rr0rr1rrr2r3rDrDrDrErs@      rc@sxeZdZejdddZejdddZejdddZejddd Zejdd d Z ejdd d Z dS)TestRetryDecoratorz time.sleepcsFtddddfdd}ttd|j|d|j|jddS)NrrN)retriesrlogfuncsxrjddqWdS)NrNr)poprD)queuerDrErIs z2TestRetryDecorator.test_retry_success..foor)r"listrrK call_count)r@sleeprIrD)r9rEtest_retry_successs z%TestRetryDecorator.test_retry_successcsDtddddfdd}ttd|jt||j|jddS)NrrN)r6rr7csxrjddqWdS)NrNr)r8rD)r9rDrErI&s z2TestRetryDecorator.test_retry_failure..foo)r"r:rrZeroDivisionErrorrKr;)r@r<rIrD)r9rEtest_retry_failure"s  z%TestRetryDecorator.test_retry_failurecCs2ttdddd}|jt||j|jddS)NrN)rrcSstdS)N) TypeErrorrDrDrDrErI3sz2TestRetryDecorator.test_exception_arg..foor)r"rrrArKr;)r@r<rIrDrDrEtest_exception_arg1s z%TestRetryDecorator.test_exception_argcCs4tdddddd}|jt||j|jddS)Nr)r6rr7cSs dddS)NrNrrDrDrDrDrErI>sz4TestRetryDecorator.test_no_interval_arg..foor)r"rr?rKr;)r@r<rIrDrDrEtest_no_interval_arg:s z'TestRetryDecorator.test_no_interval_argcCs4tdddddd}|jt||j|jddS)NrrN)r6rr7cSs dddS)NrNrrDrDrDrDrErIHsz0TestRetryDecorator.test_retries_arg..foo)r"rr?rKr;)r@r<rIrDrDrEtest_retries_argEs z#TestRetryDecorator.test_retries_argcCs|jttddddS)NrrN)r6Ztimeout)rrr")r@r<rDrDrEtest_retries_and_timeout_argsOsz0TestRetryDecorator.test_retries_and_timeout_argsN) rrrrr8r=r@rBrCrDrErDrDrDrEr5s    r5c@sDeZdZddZddZddZddZd d Zd d Zd dZ dS)TestSyncTestUtilscCs ttdS)N)r%r))r@rDrDrErVszTestSyncTestUtils.tearDownc CsPttjttjd}tjdtdgd|j tj t|WdQRXdS)Nizpsutil.tests.retry.__iter__r)r) r0r;r<maxr4Zpidsrr8iterrr>)r@ZnopidrDrDrEtest_wait_for_pidYs z#TestSyncTestUtils.test_wait_for_pidc Cs,ttd}|jdWdQRXttdS)NwrI)rr)writer/)r@rrDrDrEtest_wait_for_file_s z$TestSyncTestUtils.test_wait_for_filec Cs&ttdWdQRXttdddS)NrJT)empty)rr)r/)r@rDrDrEtest_wait_for_file_emptyes   z*TestSyncTestUtils.test_wait_for_file_emptyc Cs2tjdtdgd|jtttWdQRXdS)Nzpsutil.tests.retry.__iter__r)r)rr8rHrIOErrorr/r))r@rDrDrEtest_wait_for_file_no_fileksz,TestSyncTestUtils.test_wait_for_file_no_filec Cs0ttd}|jdWdQRXttdddS)NrJrIF)delete)rr)rKr/)r@rrDrDrEtest_wait_for_file_no_deleteos  z.TestSyncTestUtils.test_wait_for_file_no_deletecCstddd}|j|ddS)NcSsdS)NrNrDrDrDrDrEvsz3TestSyncTestUtils.test_call_until..zret == 1rN)r rK)r@rrDrDrEtest_call_untilusz!TestSyncTestUtils.test_call_untilN) rrrrrIrLrNrPrRrTrDrDrDrErFTsrFc@s(eZdZddZeZddZddZdS)TestFSTestUtilscCs ttdS)N)r%r))r@rDrDrEr|szTestFSTestUtils.setUpcCstttdjtttttjttttjdtt j dd$}|j tttWdQRXWdQRXdS)NrJzpsutil.tests.os.statr)r3) rr)closer%r;mkdirrr8rrrr)r@mrDrDrEtest_safe_rmpaths  z TestFSTestUtils.test_safe_rmpathc CsTtj}tjttt |jtjtjj|tWdQRX|jtj|dS)N)r;rrWr)rrKrrt)r@baserDrDrE test_chdirs   $zTestFSTestUtils.test_chdirN)rrrrrrYr[rDrDrDrErUzsrUc@s2eZdZddZddZeje dddZdS) TestProcessUtilscCst}tj|j}tdS)N)rr4r5r7r )r@ZsubprBrDrDrEtest_reap_childrens z#TestProcessUtils.test_reap_childrencCst\}}|j|j|jtjjdd}|jt|d|j|||j|||j|j t j |j|j |jt dS)NT) recursiver) rrTr7r4r5childrenrKrYr6rOr;r<r )r@rUrVr_rDrDrEtest_create_proc_children_pairs   z/TestProcessUtils.test_create_proc_children_pairz POSIX onlycCs4t}|jtddtj|}|j|jtjdS)NT)r^)rrr r4r5rKZstatusZ STATUS_ZOMBIE)r@ZzpidrBrDrDrEtest_create_zombie_procs z(TestProcessUtils.test_create_zombie_procN) rrrr]r`r,rrrarDrDrDrEr\s r\c@sPeZdZddZeje dddZddZeje ddd Z d d Z d S) TestNetUtilsc Cs>t}tjtd|fd}|j|jd|WdQRXdS)Nr)addrrN)r contextlibclosingr rK getsockname)r@ZportrZrDrDrEr szTestNetUtils.bind_socketz POSIX onlycCstT}t|}tj|6|j|jtj|j|jtj |j|j |WdQRXWdQRXt:}t|tj d}tj||j|jtj WdQRXWdQRXdS)N)type) r-r rdrerKfamilyrAF_UNIXrgrrf SOCK_DGRAM)r@r2rrDrDrEtest_bind_unix_sockets  z"TestNetUtils.test_bind_unix_socketcCs|dtf}ttj|d\}}tj|Ltj|6|j|j||j|j||j |j|WdQRXWdQRXdS)Nz 127.0.0.1)rc) rr(rAF_INETrdrerKrf getpeernamerT)r@rcserverclientrDrDrEtcp_tcp_socketpairs   zTestNetUtils.tcp_tcp_socketpaircCstj}|j}tv}t|\}}zP|j|j|d|jt|jddd|j|j||j|j |Wd|j |j XWdQRXdS)NrZunix)Zkind) r4r5num_fdsr-r.rKrYZ connectionsrfrmrV)r@rBrqr2rnrorDrDrEtest_unix_socketpairs z!TestNetUtils.test_unix_socketpairc Cst}tjt}tjt}x:|D]2}||jd7<||jtjtjd7<q"W|j |tj dt r|j |tj dt rtr|j |tjd|j |tjd|j |tjdWdQRXdS)NrNr)r collections defaultdictintrhZ getsockoptrZ SOL_SOCKETZSO_TYPEZassertGreaterEqualrlrrrrrirrj)r@ZsocksZfamstypesrZrDrDrEtest_create_socketss    z TestNetUtils.test_create_socketsN) rrrr r,rrrkrprrrwrDrDrDrErbs  rbc@seZdZddZdS)TestOtherUtilscCsdS)NrD)r@rDrDrEtest_is_namedtuplesz!TestOtherUtils.test_is_namedtupleN)rrrryrDrDrDrErxsrx__main__)Nrlrrsrdrrr;rrrr4rrrrrrrrZpsutil._compatr Z psutil.testsr r r r rrrrrrrrrrrrrrrrrrr r!r"r#r$r%r&r'r(r)r*r+r,r-r.r/r0ZTestCaser1r^rrrrrrr5rFrUr\rbrxrrrDrDrDrE s                                               I p  C&!&E PK!++-__pycache__/test_unicode.cpython-36.opt-1.pycnu[3 JZ[2@sdZddlZddlZddlZddlmZddlmZddlmZddlm Z ddlm Z ddlm Z dd l m Z dd l mZdd lmZdd lmZdd lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddlm$Z$ddlm%Z%dd lm&Z&ddlZddlZd!d"Zd#d$Z'e re"j(d%d&j)d%d'Z*ne"d(Z*Gd)d*d*e+Z,e%j-e oe$d+e%j-ed,e%j-e'e# d-Gd.d/d/e,e%j.Z/e%j-e o*e$d+e%j-e'e* d0Gd1d2d2e,e%j.Z0e%j-e d3Gd4d5d5e%j.Z1Gd6d7d7e%j.Z2e3d8kree4dS)9a Notes about unicode handling in psutil ====================================== In psutil these are the APIs returning or dealing with a string ('not tested' means they are not tested to deal with non-ASCII strings): * Process.cmdline() * Process.connections('unix') * Process.cwd() * Process.environ() * Process.exe() * Process.memory_maps() * Process.name() * Process.open_files() * Process.username() (not tested) * disk_io_counters() (not tested) * disk_partitions() (not tested) * disk_usage(str) * net_connections('unix') * net_if_addrs() (not tested) * net_if_stats() (not tested) * net_io_counters() (not tested) * sensors_fans() (not tested) * sensors_temperatures() (not tested) * users() (not tested) * WindowsService.binpath() (not tested) * WindowsService.description() (not tested) * WindowsService.display_name() (not tested) * WindowsService.name() (not tested) * WindowsService.status() (not tested) * WindowsService.username() (not tested) In here we create a unicode path with a funky non-ASCII name and (where possible) make psutil return it back (e.g. on name(), exe(), open_files(), etc.) and make sure that: * psutil never crashes with UnicodeDecodeError * the returned path matches For a detailed explanation of how psutil handles unicode see: - https://github.com/giampaolo/psutil/issues/1040 - http://psutil.readthedocs.io/#unicode N)closing)BSD)OPENBSD)OSX)POSIX)WINDOWS)PY3)u)APPVEYOR)ASCII_FS)bind_unix_socket)chdir)copyload_shared_lib) create_exe)get_test_subprocess)HAS_CONNECTIONS_UNIX) HAS_ENVIRON)HAS_MEMORY_MAPS)mock) reap_children)run_test_module_by_name) safe_mkdir) safe_rmpath)skip_on_access_denied)TESTFILE_PREFIX)TESTFN)TESTFN_UNICODE)TRAVIS)unittest)unix_socket_pathc Cs8tr,yt|Stk r(tjYq4Xnt|SdS)N)r _safe_rmpathZ WindowsError traceback print_exc)pathr$$/usr/lib64/python3.6/test_unicode.pyr\s  rcCsTtrdSz>y t|t|t|gdWntk r>dSXdSWdtXdS)z`Return True if both the fs and the subprocess module can deal with a unicode file name. T)cmdFN)rrrrUnicodeEncodeErrorr)namer$r$r%subprocess_supports_unicodepsr)utf8sfsurrogateescapeufÀ€c@seZdZdZeddZeddZddZdd Zd d Z d d Z ddZ ddZ ddZ eje dddZeje deje deddZddZeje deje dddZdS) _BaseFSAPIsTestsNcCst|jt|jdS)N)r funky_namer)clsr$r$r% setUpClasss z_BaseFSAPIsTests.setUpClasscCstt|jdS)N)rrr-)r.r$r$r% tearDownClasssz_BaseFSAPIsTests.tearDownClasscCs tdS)N)r)selfr$r$r%tearDownsz_BaseFSAPIsTests.tearDowncCs tddS)Nzmust be implemented in subclass)NotImplementedError)r1r$r$r%expect_exact_path_matchsz(_BaseFSAPIsTests.expect_exact_path_matchcCsHt|jgd}tj|j}|j}|j|t|jrD|j ||jdS)N)r&) rr-psutilProcesspidexeassertIsInstancestrr4 assertEqual)r1subppr8r$r$r% test_proc_exes   z_BaseFSAPIsTests.test_proc_exec Cst|jgd}trHtjdtjtjd}tj |j j }WdQRXntj |j j }|j |t |jr|j|tjj|jdS)N)r&z psutil._psplatform.cext.proc_exe) side_effect)rr-rrpatchr5 AccessDeniedosgetpidr6r7r(r9r:r4r;r#basename)r1r<mr(r$r$r%test_proc_names  z_BaseFSAPIsTests.test_proc_namecCsXt|jgd}tj|j}|j}x|D]}|j|tq(W|jrT|j ||jgdS)N)r&) rr-r5r6r7cmdliner9r:r4r;)r1r<r=rGpartr$r$r%test_proc_cmdlines  z"_BaseFSAPIsTests.test_proc_cmdlinec Csj|jd}|jt|t|t|tj}|j}WdQRX|j|jt |j rf|j ||dS)N2) r- addCleanuprrr r5r6cwdr9r:r4r;)r1dnamer=rLr$r$r% test_proc_cwds   z_BaseFSAPIsTests.test_proc_cwdc Cstj}t|j}t|jdt|j}WdQRX||jj}|j|t t rf| rf|j dS|j r|j tjj|tjj|jdS)Nrbzopen_files on BSD is broken)r5r6setZ open_filesopenr-popr#r9r:rZskipTestr4r;rBnormcase)r1r=startnewr#r$r$r%test_proc_open_filess    z%_BaseFSAPIsTests.test_proc_open_filesz POSIX onlycCstjj|j}t|d}y t|}Wn&tk rLtr>n tj dYnXt |8t j j dd}|j|jtts|j|j|WdQRXWdQRXdS)N)suffixz not supportedunixr)rBr#rDr-rr r'rrSkipTestrr5r6Z connectionsr9laddrr:rr;)r1rWr(sockconnr$r$r%test_proc_connectionss   z&_BaseFSAPIsTests.test_proc_connectionszcan't list UNIX socketscCsdd}tjj|j}t|d}y t|}Wn&tk rTtrFn tj dYnXt |:t j dd}t s||}|j|jt|j|j|WdQRXWdQRXdS)NcSs2x$|D]}tjj|jjtr|SqWtddS)Nzconnection not found)rBr#rDrZ startswithr ValueError)consr\r$r$r% find_socks z8_BaseFSAPIsTests.test_net_connections..find_sock)rWz not supportedrX)Zkind)rBr#rDr-rr r'rrrYrr5Znet_connectionsrr9rZr:r;)r1rarWr(r[r`r\r$r$r%test_net_connectionss    z%_BaseFSAPIsTests.test_net_connectionscCs,|jd}|jt|t|tj|dS)NrJ)r-rKrrr5Z disk_usage)r1rMr$r$r%test_disk_usage s  z _BaseFSAPIsTests.test_disk_usagez not supportedz&ctypes does not support unicode on PY2c svt|jd`}ddfddtjjD}dd|D}|j||x|D]}|j|tqTWWdQRXdS)N)Z dst_prefixcSstjjtjj|S)N)rBr#realpathrS)r=r$r$r%normpathsz3_BaseFSAPIsTests.test_memory_maps..normpathcsg|]}|jqSr$)r#).0x)rer$r% sz5_BaseFSAPIsTests.test_memory_maps..cSsg|]}t|kr|qSr$)r)rfrgr$r$r%rhs)rr-r5r6Z memory_mapsZassertInr9r:)r1Z funky_pathZlibpathsr#r$)rer%test_memory_mapss  z!_BaseFSAPIsTests.test_memory_maps)__name__ __module__ __qualname__r- classmethodr/r0r2r4r>rFrIrNrVrskipIfrr]rrrbrcrrrir$r$r$r%r,s"       r,zunreliable on TRAVISzASCII fsz"subprocess can't deal with unicodec@s eZdZdZeZeddZdS) TestFSAPIsz1Test FS APIs with a funky, valid, UTF8 path name.c CsNtrdSt|jtrdntd}tjtjd|jtj |kSQRXdS)NT.ignore) r isinstancer-r:r warningscatch_warnings simplefilterrBlistdir)r.herer$r$r%r4(s   z"TestFSAPIs.expect_exact_path_matchN)rjrkrl__doc__rr-rmr4r$r$r$r%ro sroz*subprocess can't deal with invalid unicodec@s eZdZdZeZeddZdS)TestFSAPIsWithInvalidPathz-Test FS APIs with a funky, invalid path name.cCsdS)NTr$)r.r$r$r%r4<sz1TestFSAPIsWithInvalidPath.expect_exact_path_matchN)rjrkrlrx INVALID_NAMEr-rmr4r$r$r$r%ry5sryz WINDOWS onlyc@seZdZddZdS)TestWinProcessNamec Cs<tjdtjtjd}|jtjjt WdQRXdS)Nz psutil._psplatform.cext.proc_exe)r?) rr@r5rArBrCr9r6r(r:)r1rEr$r$r%test_name_typeEsz!TestWinProcessName.test_name_typeN)rjrkrlr|r$r$r$r%r{Bsr{c@s.eZdZdZddZeje dddZdS) TestNonFSAPISz&Unicode tests for non fs-related APIs.cCs tdS)N)r)r1r$r$r%r2WszTestNonFSAPIS.tearDownz not supportedcCs~tjj}trtnd}||d<t|d}tj|j}|j}x,|j D] \}}|j |t |j |t qFW|j |d|dS)NèZ FUNNY_ARG)env) rBenvironcopyrrrr5r6r7itemsr9r:r;)r1rZ funky_strZsprocr=kvr$r$r%test_proc_environZs     zTestNonFSAPIS.test_proc_environN) rjrkrlrxr2rrnrrr$r$r$r%r}Tsr}__main__)5rxrBr!rs contextlibrr5rrrrrZpsutil._compatrr Z psutil.testsr r r r rrrrrrrrrrrr rrrrrrrr)encodedecoderzobjectr,rnZTestCaseroryr{r}rj__file__r$r$r$r%4sr                                     PK!oo'__pycache__/test_windows.cpython-36.pycnu[3 JZK@s`dZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl m Z ddlmZddlmZddlmZddlmZddlmZdd lmZdd lmZdd lmZdd lmZdd lmZe jZe jdy$ddlZddlZddlZddlZWn$e k rDej!dkr@YnXWdQRXe j"j#Z#e j$d$kZ%ddZ&ej'e dGdddej(Z)ej'e dGdddej(Z*ej'e dGdddej(Z+ej'e dGdddej(Z,ej'e dGdddej(Z-ej'e dGdd d ej(Z.ej'e dGd!d"d"ej(Z/e0d#kr\ee1dS)%zWindows specific tests.N)WINDOWS)callable)APPVEYOR)get_test_subprocess) HAS_BATTERY)mock) reap_children)retry_before_failing)run_test_module_by_name)sh)unittestignorent csfdd}|S)Ncsty|f||Stk rn}zBddlm}|j|krDtjdd|jtjkr\tjddWYdd}~XnXdS)Nr)ACCESS_DENIED_SET)OSErrorZpsutil._pswindowsrerrnopsutil AccessDeniedZESRCH NoSuchProcess)selfargskwargserrr)fun$/usr/lib64/python3.6/test_windows.pywrapper5s     z wrap_exceptions..wrapperr)rrr)rrwrap_exceptions4s rz WINDOWS onlyc@seZdZddZejdejkdddZddZ d d Z d d Z eje d e ddZe ddZddZddZddZddZddZdS)TestSystemAPIscCsVtd}tjddj}x8|D]0}d|jddjkr8q||kr|jd|qWdS)Nz ipconfig /allT)Zperniczpseudo-interface -z-%r nic wasn't found in 'ipconfig /all' output)r rZnet_io_counterskeysreplacelowerfail)routZnicsZnicrrrtest_nic_namesJs zTestSystemAPIs.test_nic_namesNUMBER_OF_PROCESSORSz-NUMBER_OF_PROCESSORS env var is not availablecCs"ttjd}|j|tjdS)Nr))intosenviron assertEqualr cpu_count)rZnum_cpusrrrtest_cpu_countTszTestSystemAPIs.test_cpu_countcCs$tjd}tj}|j||dS)N)win32apiZ GetSystemInforr.r-)r sys_value psutil_valuerrrtest_cpu_count_2Zs zTestSystemAPIs.test_cpu_count_2cCs@tj}|jd}|j|jtjj|j|jtjj dS)Nr) wmiWMIZWin32_Processorr-ZCurrentClockSpeedrZcpu_freqZcurrentZ MaxClockSpeedmax)rwprocrrr test_cpu_freq_s zTestSystemAPIs.test_cpu_freqcCs,tjjd}|jt|jtjjdS)Nr) r5r6ZWin32_ComputerSystemr-r*ZTotalPhysicalMemoryrZvirtual_memorytotal)rr8rrrtest_total_phymemes z TestSystemAPIs.test_total_phymemztest not relieable on appveyorcCs:tjj}tdd|D}ttj}|j||dS)NcSsg|] }|jqSr) ProcessId).0xrrr |sz,TestSystemAPIs.test_pids..)r5r6 Win32_ProcesssetrZpidsr-)rr8Zwmi_pidsZ psutil_pidsrrr test_pidsvs  zTestSystemAPIs.test_pidscCstjdd}tjj}x|D]}x|D]}|jjdd|jkr(|jsHPytj |j}Wn4t k r}z|j t j krzPnWYdd}~XnX|j |jt|jt|j}|j |j|t|j|d kr|jd|j|fPq(W|jdt|qWdS) NT)all\ izpsutil=%s, wmi=%szcan't find partition %si(i)rdisk_partitionsr5r6ZWin32_LogicalDiskZdevicer$ZDeviceID mountpoint disk_usagerrENOENTr-r;r*ZSizeZ FreeSpacefreeabsr&repr)rZps_partsZ wmi_partsZps_partZwmi_partZusagerZwmi_freerrr test_diskss*      zTestSystemAPIs.test_diskscCspxjtjD]^}tj|j}tj|j}|j|d|jdd|j|d|jdd|j |j |j|jq WdS)Nri)deltaii) rrHr1ZGetDiskFreeSpaceExrIrJassertAlmostEqualrLr;r-Zused)rZdiskr2r3rrrtest_disk_usages  zTestSystemAPIs.test_disk_usagecCs>ddtjjdD}ddtjddD}|j||dS)NcSs$g|]}|r|jd r|dqS)zA:rE) startswith)r>r?rrrr@sz7TestSystemAPIs.test_disk_partitions..z\cSsg|] }|jqSr)rI)r>r?rrrr@sT)rD)r1ZGetLogicalDriveStringssplitrrHr-)rr2r3rrrtest_disk_partitionssz#TestSystemAPIs.test_disk_partitionscCs`ttj}tjj}t}x$|D]}|j|j|j|jq$W|j ||@d||fdS)Nzno common entries in %s, %s) rBcextZ net_if_statsr5r6ZWin32_NetworkAdapteraddNameZNetConnectionID assertTrue)rZps_namesZ wmi_adaptersZ wmi_namesZ wmi_adapterrrrtest_net_if_statss     z TestSystemAPIs.test_net_if_statscCs^tjj}|djjdd}tjj|d}tjjtj }t ||j }|j |ddS)Nr.z %Y%m%d%H%M%S) r5r6ZWin32_OperatingSystemZLastBootUpTimerUdatetimeZstrptimeZ fromtimestampr boot_timerMZ total_secondsZassertLessEqual)rZwmi_osZ wmi_btime_strZ wmi_btime_dtZ psutil_dtZdiffrrrtest_boot_times zTestSystemAPIs.test_boot_timecCstjddd|jtjdWdQRXtjddd|jtjdWdQRXtjddd|jtjdWdQRXtjddd|jtjdWdQRXdS)Nz psutil._pswindows.cext.boot_timer0) return_valueiM)rpatchr-rr_)rrrrtest_boot_time_fluctuationsz)TestSystemAPIs.test_boot_time_fluctuationN)__name__ __module__ __qualname__r(r skipIfr+r,r/r4r:r<rr rCrOrSrVr[r`rerrrrr Gs      r c@s`eZdZddZeje dddZeje dddZdd Z d d Z d d Z ddZ dS)TestSensorsBatterycCs.tjdr|jtjn|jtjdS)NZSystemBatteriesPresent)r1ZGetPwrCapabilitiesZassertIsNotNonersensors_battery assertIsNone)rrrrtest_has_batterys z#TestSensorsBattery.test_has_batteryz no batterycCs6tj}|jdd}tj}|j|j|jdddS)Nzselect * from Win32_BatteryrrQ)rP)r5r6queryrrkrRZpercentZEstimatedChargeRemaining)rr8 battery_wmibattery_psutilrrr test_percents zTestSensorsBattery.test_percentcCs6tj}|jdd}tj}|j|j|jdkdS)Nzselect * from Win32_Batteryrr)r5r6rnrrkr-Z power_pluggedZ BatteryStatus)rr8rorprrrtest_power_pluggeds z%TestSensorsBattery.test_power_pluggedc Cs6tjddd}|jtj|js(tWdQRXdS)Nz&psutil._pswindows.cext.sensors_batteryr)ra)rrsrr)rrdrlrrkcalledAssertionError)rmrrrtest_emulate_no_batterys z*TestSensorsBattery.test_emulate_no_batteryc Cs<tjddd$}|jtjjtj|js.tWdQRXdS)Nz&psutil._pswindows.cext.sensors_batteryrQr)ra)rQrrr) rrdr-rrksecsleftPOWER_TIME_UNLIMITEDrtru)rrvrrrtest_emulate_power_connecteds   z/TestSensorsBattery.test_emulate_power_connectedc Cs<tjddd$}|jtjjtj|js.tWdQRXdS)Nz&psutil._pswindows.cext.sensors_batteryr)ra)rr{rr) rrdr-rrkrxryrtru)rrvrrrtest_emulate_power_chargings   z.TestSensorsBattery.test_emulate_power_chargingc Cs<tjddd$}|jtjjtj|js.tWdQRXdS)Nz&psutil._pswindows.cext.sensors_batteryrrQ)ra)rrrr}) rrdr-rrkrxZPOWER_TIME_UNKNOWNrtru)rrvrrrtest_emulate_secs_left_unknowns   z1TestSensorsBattery.test_emulate_secs_left_unknownN) rfrgrhrmr rirrqrrrwrzr|r~rrrrrjs  rjc@seZdZeddZeddZddZddZd d Zd d Z d dZ ddZ ddZ e jejd+k dddZddZddZddZddZd d!Zd"d#Zd$d%Zd&d'Zd(d)Zd*S), TestProcesscCstj|_dS)N)rpid)clsrrr setUpClassszTestProcess.setUpClasscCs tdS)N)r)rrrr tearDownClassszTestProcess.tearDownClasscCstjd}|jtj|jdS)Nr)rProcess assertRaisesrkill)rprrr test_issue_24s zTestProcess.test_issue_24c Cstjd}|j|jdt||j|j|jdky|jdd\}}Wn(tj k r|t j dd krxYnX|j|d kdS) NrbZSystemgrrQvistawin-7win7r)rrr) rrr-namestrusernamerZ create_time memory_inforplatformuname)rrrssvmsrrrtest_special_pid s zTestProcess.test_special_pidcCs"tj|j}|jt|jtjdS)N)rrrr ValueError send_signalsignalSIGINT)rrrrrtest_send_signal1s zTestProcess.test_send_signalc CsNxHtjD]<}y |jtjj|j|jWq tjk rDYq Xq WdS)N) r process_iterr-r+pathbasenameexerError)rrrrrtest_exe5s  zTestProcess.test_execCsbtjtj}|j}tjtjtj tj}|j}|j ||dtj ||j |j|dS)NrQ) rrr+getpid num_handlesr1 OpenProcesswin32conPROCESS_QUERY_INFORMATIONFALSEr- CloseHandle)rrZbeforehandleafterrrrtest_num_handles_increment<s z&TestProcess.test_num_handles_incrementc sfdd}tj|j}g}xttjD]jds(dkrBq(q(y(|||j}|||j}Wntjtjfk rYq(X||kr(d||f}|j|q(W|r|j ddj |dS)Ncs,t|d}|dk r$t|r$|n|dS)N)getattrr)rattr)rrrcallJs z+TestProcess.test_handles_leak..call_ terminatersuspendresumenicerwaitchildrenas_dictmemory_info_exz@failure while processing Process.%s method (before=%s, after=%s) ) rrrrrrrrrr) rrrdirrTrrrappendr&join)rrrZfailuresZnum1Znum2r&r)rrtest_handles_leakFs,       zTestProcess.test_handles_leakc Cs:x4tjD](}y |jWq tjk r0Yq Xq WdS)N)rrrr)rrrrrtest_name_always_availablejs  z&TestProcess.test_name_always_availablerzCTRL_* signals not supportedcCsbtjtj}|jtj|jtj|j|j |j tj |jtj|j tj |jtjdS)N) rrrrrrZ CTRL_C_EVENTZCTRL_BREAK_EVENTrrrr)rrrrrtest_ctrl_signalsss   zTestProcess.test_ctrl_signalsc Cs\xVtjD]J}ytjj|j}|j}Wntjtjfk rFYq X|j ||q WdS)N) rrr+rrrrrrr-)rrabrrrtest_compare_name_exes z!TestProcess.test_compare_name_execCs |jtjjtjtjdS)N)r-rrrr1Z GetUserNameExrZNameSamCompatible)rrrr test_usernameszTestProcess.test_usernamecCs8tjddtjj}djtjj}|j ||dS)Nz +r!) resubr1ZGetCommandLinestriprrrcmdliner-)rr2r3rrr test_cmdlineszTestProcess.test_cmdlinecCsJtjtjtjtj}|jtj|t j |}t j j }|j||dS)N)r1rrrrr+r addCleanupr win32processZGetPriorityClassrrrr-)rrr2r3rrr test_nices   zTestProcess.test_nicecCstjtjtj|j}|jtj|tj |}t j |jj }|j |d|j|j |d|j|j |d|j|j |d|j|j |d|j|j |d|j|j |d|j|j |d|j|j |j|j|j |j|jdS) NZPeakWorkingSetSizeWorkingSetSizeZQuotaPeakPagedPoolUsageZQuotaPagedPoolUsageZQuotaPeakNonPagedPoolUsageZQuotaNonPagedPoolUsageZ PagefileUsageZPeakPagefileUsage)r1rrrrrrrrZGetProcessMemoryInforrrr-Z peak_wsetZwsetZpeak_paged_poolZ paged_poolZpeak_nonpaged_poolZ nonpaged_poolZpagefileZ peak_pagefilerr)rrr2r3rrrtest_memory_infos0  zTestProcess.test_memory_infocCsXtjtjtj|j}|jtj|tj |j}|j |j }t j |}|j||dS)N)r1rrrrrrrrrrrrZGetExitCodeProcessr-)rrrr3r2rrr test_waits   zTestProcess.test_waitcCs\dd}tjtjtj|j}|jtj||tj |d}t j |jj }|j ||dS)NcsfddtdDS)Ncsg|]}d|>@r|qS)rQr)r>i)r?rrr@szGTestProcess.test_cpu_affinity..from_bitmask..@)range)r?r)r?r from_bitmasksz3TestProcess.test_cpu_affinity..from_bitmaskr)r1rrrrrrrrZGetProcessAffinityMaskrrZ cpu_affinityr-)rrrr2r3rrrtest_cpu_affinitys zTestProcess.test_cpu_affinitycCstjtjtjtj}|jtj|t j |}t j j }|j|j|d|j|j|d|j|j|d|j|j|d|j|j|d|j|j|ddS)NZReadOperationCountZWriteOperationCountZReadTransferCountZWriteTransferCountZOtherOperationCountZOtherTransferCount)r1rrrrr+rrrrZGetProcessIoCountersrr io_countersr-Z read_countZ write_countZ read_bytesZ write_bytes other_countZ other_bytes)rrr2r3rrrtest_io_counterss"  zTestProcess.test_io_counterscCsddl}ddl}d}|jjj|dtj}|j|jjj||j j }|jjj ||j ||j }tjj}|jjj||j||ddS)NrirQ)ctypesZctypes.wintypesZwindllZkernel32rr+rrrZwintypesZDWORDZGetProcessHandleCountZbyrefvaluerrrr-)rrrrZhndcntr2r3rrrtest_num_handless  zTestProcess.test_num_handlesN)rr)rfrgrh classmethodrrrrrrrrrr risys version_inforrrrrrrrrrrrrrrs(   $     rc@s`eZdZdZeddZeddZddZdd Zd d Z d d Z ddZ ddZ ddZ dS)TestProcessWMIz%Compare Process API results with WMI.cCstj|_dS)N)rr)rrrrrszTestProcessWMI.setUpClasscCs tdS)N)r)rrrrrszTestProcessWMI.tearDownClasscCs8tjj|jdd}tj|j}|j|j|jdS)N)r=r) r5r6rArrrr-rZCaption)rr8rrrr test_name s zTestProcessWMI.test_namecCs@tjj|jdd}tj|j}|j|jj|j jdS)N)r=r) r5r6rArrrr-rr%ZExecutablePath)rr8rrrrrs zTestProcessWMI.test_execCsFtjj|jdd}tj|j}|jdj|j|j j dddS)N)r=rr!"rF) r5r6rArrrr-rrZ CommandLiner$)rr8rrrrrs zTestProcessWMI.test_cmdlinecCsPtjj|jdd}tj|j}|j\}}}d||f}|j|j|dS)N)r=rz%s\%s) r5r6rArrrZGetOwnerr-r)rr8rZdomainrrrrrrs   zTestProcessWMI.test_usernamecCsLtjdtjj|jdd}tj|j}|jj }|j |t |j dS)Ng?)r=r) timesleepr5r6rArrrrrr-r*r)rr8rrrrrtest_memory_rss#s    zTestProcessWMI.test_memory_rsscCsjtjdtjj|jdd}tj|j}|jj }t |j }||krf||dkrf|j d||fdS)Ng?)r=rizwmi=%s, psutil=%s) rrr5r6rArrrrrr*Z PageFileUsager&)rr8rrZ wmi_usagerrrtest_memory_vms*s    zTestProcessWMI.test_memory_vmscCs\tjj|jdd}tj|j}t|jjdd}t j dt j |j }|j ||dS)N)r=rr\z %Y%m%d%H%M%S)r5r6rArrrrZ CreationDaterUrZstrftimeZ localtimerr-)rr8rZ wmic_createZ psutil_createrrrtest_create_time7s  zTestProcessWMI.test_create_timeN)rfrgrh__doc__rrrrrrrrrrrrrrrs   rc@sXeZdZdZeddZeddZddZdd Zd d Z d d Z ddZ ddZ dS)TestDualProcessImplementationa{ Certain APIs on Windows have 2 internal implementations, one based on documented Windows APIs, another one based NtQuerySystemInformation() which gets called as fallback in case the first fails because of limited permission error. Here we test that the two methods return the exact same value, see: https://github.com/giampaolo/psutil/issues/304 cCstj|_dS)N)rr)rrrrrLsz(TestDualProcessImplementation.setUpClasscCs tdS)N)r)rrrrrPsz+TestDualProcessImplementation.tearDownClassc CsZtj|jj}tjdtjtjd(}|j tj|jj||j sLt WdQRXdS)Nz psutil._psplatform.cext.proc_exe) side_effect) rrrrrrdrr+rr-rtru)rrrrrrrWs z'TestDualProcessImplementation.test_namec Cstj|jj}tjdttjdd}tj|jj}|j t |t |xLt t |D]<}|j ||d|j ||d|j ||||ddqZW|jstWdQRXdS)Nz(psutil._psplatform.cext.proc_memory_infomsg)rri)rP)rrrrrrdrrEPERMr-lenrZassertGreaterEqualrRrtru)rZmem_1rZmem_2rrrrr^sz.TestDualProcessImplementation.test_memory_infoc CsXtj|jj}tjdttjdd(}|j tj|jj||j sJt WdQRXdS)Nz(psutil._psplatform.cext.proc_create_timer)r) rrrrrrdrrrr-rtru)rZctimerrrrrjs z.TestDualProcessImplementation.test_create_timec Csxtj|jj}tjdttjddH}tj|jj}|j sBt |j |j |j dd|j |j |j ddWdQRXdS)Nz&psutil._psplatform.cext.proc_cpu_timesr)rg{Gz?)rP)rrrZ cpu_timesrrdrrrrtrurRusersystem)rZ cpu_times_1rZ cpu_times_2rrrtest_cpu_timesqs z,TestDualProcessImplementation.test_cpu_timesc Cs~tj|jj}tjdttjddN}tj|jj}x,t t |D]}|j ||||ddqFW|j spt WdQRXdS)Nz(psutil._psplatform.cext.proc_io_countersr)rr0)rP)rrrrrrdrrrrrrRrtru)rZ io_counters_1rZ io_counters_2rrrrr|sz.TestDualProcessImplementation.test_io_countersc CsXtj|jj}tjdttjdd(}|j tj|jj||j sJt WdQRXdS)Nz(psutil._psplatform.cext.proc_num_handlesr)r) rrrrrrdrrrr-rtru)rrrrrrrs z.TestDualProcessImplementation.test_num_handlesN) rfrgrhrrrrrrrrrrrrrrr@s      rc@s|eZdZdZeddZeddZddgZdd Z d d Z ed d Z ddZ ddZ ddZddZddZddZdS)RemoteProcessTestCasezCertain functions require calling ReadProcessMemory. This trivially works when called on the current process. Check that this works on other processes, especially when they have a different bitness. cCsTd}xJtjdD]<}tj|d|gtjtjd}|j\}}|tt kr|SqWdS)Nz6import sys; sys.stdout.write(str(sys.maxsize > 2**32))zC:\Python*\python.exez-c)rstdoutstderr)glob subprocessPopenPIPEZSTDOUT communicater IS_64_BIT)codefilenamer9outputrrrrfind_other_interpreters   z,RemoteProcessTestCase.find_other_interpretercCs@|j}|dkrtjdtr.tj|_||_n||_tj|_dS)Nz0could not find interpreter with opposite bitness)rr ZSkipTestrr executablepython64python32)rZ other_pythonrrrrsz RemoteProcessTestCase.setUpClassz-czimport sys; sys.stdin.read()cCsVtjj}ttj|d<t|jg|j|tj d|_ t|j g|j|tj d|_ dS)NTHINK_OF_A_NUMBER)envstdin) r+r,copyrrrr test_argsrrproc32rproc64)rrrrrsetUps  zRemoteProcessTestCase.setUpcCs|jj|jjtdS)N)rrrr)rrrrtearDowns  zRemoteProcessTestCase.tearDowncCs tdS)N)r)rrrrrsz#RemoteProcessTestCase.tearDownClasscCs@tj|jj}|jt|jd|j|jdd|jdS)Nr]rQ)rrrrr-rrr)rrrrrtest_cmdline_32sz%RemoteProcessTestCase.test_cmdline_32cCs@tj|jj}|jt|jd|j|jdd|jdS)Nr]rQ)rrrrr-rrr)rrrrrtest_cmdline_64sz%RemoteProcessTestCase.test_cmdline_64cCs&tj|jj}|j|jtjdS)N)rrrrr-cwdr+getcwd)rrrrr test_cwd_32sz!RemoteProcessTestCase.test_cwd_32cCs&tj|jj}|j|jtjdS)N)rrrrr-rr+r )rrrrr test_cwd_64sz!RemoteProcessTestCase.test_cwd_64cCs>tj|jj}|j}|jd||j|dttj dS)Nr) rrrrr,assertIn assertEqualsrr+r)rrerrrtest_environ_32s z%RemoteProcessTestCase.test_environ_32cCs>tj|jj}|j}|jd||j|dttj dS)Nr) rrrrr,r r rr+r)rrrrrrtest_environ_64s z%RemoteProcessTestCase.test_environ_64N)rfrgrhr staticmethodrrrrrrrrrr r rrrrrrrs    rc@seZdZddZddZdS) TestServicescCsntdddddddg}tdd d g}tddd d d ddg}x,tjD]}|j}|j|dt|j|djd|j|dt|j|dt|j|d||ddk rtj |d|j|dt|j|dt|j|dt|j|d||j|d||j|dt|j }|dk rLtj |}|j |j tj |j}|j||qFWdS)NZrunningZpausedstartpausecontinuestopZstoppedZ automaticZmanualZdisabledZ start_pendingZ pause_pendingZcontinue_pendingZ stop_pendingrrF display_namerstatusrZbinpathZ start_type description)rBrwin_service_iterrZassertIsInstancerZassertNotEqualrr rrrZZ is_runningwin_service_getrr-)rZvalid_statusesZvalid_start_typesZservdatarrsrrrtest_win_service_itersR   z"TestServices.test_win_service_iterc'Cspttjj}|jtj}tj|dWdQRX|j|jj|dtj|}t tj j j d}t jd|d|jtj|jWdQRXt jd|d|jtj|jWdQRXt tj j jd}t jd|d|jtj|jWdQRXt jd|d|jtj|jWdQRX|j|jt||j|jt||j|jt||j|jt|dS)Nz???rFz/psutil._psplatform.cext.winservice_query_status)rz/psutil._psplatform.cext.winservice_query_config)nextrrrrrrr-Z exceptionZ WindowsError _psplatformrWZERROR_SERVICE_DOES_NOT_EXISTrrdrrZERROR_ACCESS_DENIEDrr rrrN)rrcmZserviceexcrrrtest_win_service_get!s2     z!TestServices.test_win_service_getN)rfrgrhrr#rrrrrs0r__main__l)2rr^rrr+rrrrrrwarningsrrZpsutil._compatrZ psutil.testsrrrrrr r r r catch_warnings simplefilterr1rrr5 ImportErrorrr rWmaxsizerrriZTestCaser rjrrrrrrf__file__rrrrsl                   < m A N ^ U PK!+__pycache__/test_linux.cpython-36.opt-1.pycnu[3 JZ3@sdZddlmZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl Z ddlZddlZddlZddlZddlZddlmZddlmZddlmZddlmZddlmZdd lmZdd lmZdd lmZdd lmZdd lmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddlm$Z$ddlm%Z%ddlm&Z&ddlm'Z'ddlm(Z(ddlm)Z)ddlm*Z*ddlm+Z+ej,j-ej,j.e/Z0dZ1dZ2dZ3erdZ4dd Z5d!d"Z6d#d$Z7d%d&Z8d'd(Z9d)d*Z:e*j;e d+Gd,d-d-e*j<Z=e*j;e d+Gd.d/d/e*j<Z>e*j;e d+Gd0d1d1e*j<Z?e*j;e d+Gd2d3d3e*j<Z@e*j;e d+Gd4d5d5e*j<ZAe*j;e d+Gd6d7d7e*j<ZBe*j;e d+Gd8d9d9e*j<ZCe*j;e d+e*j;e d:Gd;d<dd>e*j<ZEe*j;e d+Gd?d@d@e*j<ZFe*j;e d+GdAdBdBe*j<ZGe*j;e d+GdCdDdDe*j<ZHe*j;e d+GdEdFdFe*j<ZIeJdGkre#e/dS)HzLinux specific tests.)divisionN)LINUX)PY3)u) call_until) HAS_BATTERY) HAS_CPU_FREQ) HAS_RLIMIT)MEMORY_TOLERANCE)mock)PYPY)pyrun) reap_children) reload_module)retry_before_failing)run_test_module_by_name) safe_rmpath)sh)skip_on_not_implemented)TESTFN) ThreadTask)TRAVIS)unittest)whichiii'icCspddl}|dd}tr"t|d}tjtjtj}tj|*tj|j |j t t j d|ddSQRXdS)Nrascii256s)fcntlrbytessocketAF_INET SOCK_DGRAM contextlibclosingZ inet_ntoaioctlfileno SIOCGIFADDRstructpack)ifnamersr-"/usr/lib64/python3.6/test_linux.pyget_ipv4_address@s    r/c sddl}|dd}tr"t|d}tjtjtj}tj|`|j|j t t j d|}trfddnddl }|jdjfdd |d d Ddd SQRXdS)NrrrrcSs|S)Nr-)xr-r-r.ordWszget_mac_address..ordcsg|]}d|qS)z%02x:r-).0char)r1r-r. \sz#get_mac_address..r)rrr r!r"r#r$r%r&r' SIOCGIFHWADDRr)r* __builtin__r1join)r+rr,infor:r-)r1r.get_mac_addressMs    r=cCsttd}|jd}xJ|D]B}|jdr|j\}}}}tjdd}|t|t|t|SqWtddj|dS)zQParse 'free' cmd and return swap memory's s total, used and free values. zfree -b ZSwapfreeztotal used freez&can't find 'Swap' in 'free' output: %sN)rsplit startswith collections namedtupleint ValueErrorr;)outlinesline_totalusedr?ntr-r-r. free_swap_s    rMcCs~td}|jd}xT|D]L}|jdrdd|jddD\}}}}tjdd }||||||SqWtd dj|d S) zSParse 'free' cmd and return physical memory's total, used and free values. zfree -br>ZMemcSsg|] }t|qSr-)rD)r3r0r-r-r.r5{sz free_physmem..r7r?ztotal used free shared outputz%can't find 'Mem' in 'free' output: %sN)rr@rArBrCrEr;)rFrGrHrJrKr?sharedrLr-r-r. free_physmemns   "rPcCsNtd}x4|jdD]&}|j}||krt|jddSqWtd|dS)Nz vmstat -sr> rz can't find %r in 'vmstat' output)rr@striprDrE)statrFrHr-r-r.vmstats rTcCs(tdj}ttt|jdjdS)Nzfree -Vr7.r8)rrRtuplemaprDr@)rFr-r-r.get_free_version_infos rXz LINUX onlyc@seZdZddZejeo ed kdeddZ eje ded d Z ed d Z eje ded dZ eje deddZeddZeddZddZddZddZddZddZdS)!TestSystemVirtualMemorycCs&tdd}tjj}|j||dS)Nz total memoryi)rTpsutilvirtual_memoryrJassertAlmostEqual)self vmstat_value psutil_valuer-r-r. test_totals  z"TestSystemVirtualMemory.test_total zold free versioncCs8t}|j}tjj}|j||td|||jfddS)Nz %s %s %s)deltamsg)rPrKrZr[r\r output)r]r? free_valuer_r-r-r. test_useds  z!TestSystemVirtualMemory.test_usedzunreliable on TRAVIScCs*tdd}tjj}|j||tddS)Nz free memoryi)rc)rTrZr[r?r\r )r]r^r_r-r-r. test_frees  z!TestSystemVirtualMemory.test_freecCs*tdd}tjj}|j||tddS)Nz buffer memoryi)rc)rTrZr[buffersr\r )r]r^r_r-r-r. test_bufferss  z$TestSystemVirtualMemory.test_bufferscCs*tdd}tjj}|j||tddS)Nz active memoryi)rc)rTrZr[activer\r )r]r^r_r-r-r. test_actives  z#TestSystemVirtualMemory.test_activecCs*tdd}tjj}|j||tddS)Nzinactive memoryi)rc)rTrZr[inactiver\r )r]r^r_r-r-r. test_inactives  z%TestSystemVirtualMemory.test_inactivecCsJt}|j}|dkrtjdtjj}|j||td|||jfddS)Nrz%free does not support 'shared' columnz %s %s %s)rcrd) rPrOrSkipTestrZr[r\r re)r]r?rfr_r-r-r. test_shareds  z#TestSystemVirtualMemory.test_sharedcCshtd}|jd}d|dkr*tjdn:t|djd }tjj}|j||t d|||fddS) Nzfree -br> availablerz(free does not support 'available' columnr7z %s %s %s)rcrdr8) rr@rrorDrZr[rqr\r )r]rFrGrfr_r-r-r.test_availables    z&TestSystemVirtualMemory.test_availablecsTfdd}ttrdnd}tj|d|d}tjdd}tjdtj}|j t |d |d }|j d t |j |j d t |j |j d t |j |j dt |j |j dt |j |j dt |j |j dt |j |j |jd |j |jd |j |jd |j |jd |j |jd |j |jd WdQRXWdQRXdS)Ncs0|dkrtjtjdjS|f||SdS)Nz /proc/meminfoa Active(anon): 6145416 kB Active(file): 2950064 kB Inactive(anon): 574764 kB Inactive(file): 1567648 kB MemAvailable: -1 kB MemFree: 2057400 kB MemTotal: 16325648 kB SReclaimable: 346648 kB )ioBytesIOtextwrapdedentencode)nameargskwargs) orig_openr-r. open_mocks zBTestSystemVirtualMemory.test_warnings_on_misses..open_mockz builtins.openz__builtin__.openT)create side_effect)recordalwaysr7rz#memory stats couldn't be determinedcachedrOrkrmrirq)openrr patchwarningscatch_warnings simplefilterrZr[ assertEquallenassertInstrmessagerrkrmrOrirq)r]r| patch_pointmwsretwr-)r{r.test_warnings_on_missess.   z/TestSystemVirtualMemory.test_warnings_on_missesc Csddlm}ddlm}i}|d4}x,|D]$}|j}t|dd||d<q,WWdQRX||}d|kr|d}t|||d} |j| d dS) Nr)calculate_avail_vmem) open_binaryz /proc/meminfor7is MemAvailable:d )psutil._pslinuxrrr@rDabsZ assertLess) r]rrZmemsfrHfieldsabZ diff_percentr-r-r.test_avail_old_percents    &z.TestSystemVirtualMemory.test_avail_old_percentcsfdd}ttrdnd}tj|d|dN}tjdd}tj}WdQRX|j|j d |d }|j d t |j WdQRXdS) Ncs0|dkrtjtjdjS|f||SdS)Nz /proc/meminfoa Active: 9444728 kB Active(anon): 6145416 kB Active(file): 2950064 kB Buffers: 287952 kB Cached: 4818144 kB Inactive(file): 1578132 kB Inactive(anon): 574764 kB Inactive(file): 1567648 kB MemAvailable: 6574984 kB MemFree: 2057400 kB MemTotal: 16325648 kB Shmem: 577588 kB SReclaimable: 346648 kB )rsrtrurvrw)rxryrz)r{r-r.r|0s zKTestSystemVirtualMemory.test_avail_old_comes_from_kernel..open_mockz builtins.openz__builtin__.openT)r}r~)riSdirz,inactive memory stats couldn't be determinedl ") rrr rrrrZr[rrqrrr)r]r|rrrrrr-)r{r. test_avail_old_comes_from_kernel-s  z8TestSystemVirtualMemory.test_avail_old_comes_from_kernelcsfdd}ttrdnd}tj|d|dN}tjdd}tj}WdQRX|j|j d|d }|j d t |j WdQRXdS)Ncs0|dkrtjtjdjS|f||SdS)Nz /proc/meminfoa Active: 9444728 kB Active(anon): 6145416 kB Buffers: 287952 kB Cached: 4818144 kB Inactive(file): 1578132 kB Inactive(anon): 574764 kB MemFree: 2057400 kB MemTotal: 16325648 kB Shmem: 577588 kB )rsrtrurvrw)rxryrz)r{r-r.r|Ss zHTestSystemVirtualMemory.test_avail_old_missing_fields..open_mockz builtins.openz__builtin__.openT)r}r~)ridiiIrz,inactive memory stats couldn't be determinedi}l'Ll`LG) rrr rrrrZr[rrqrrr)r]r|rrrrrr-)r{r.test_avail_old_missing_fieldsOs  z5TestSystemVirtualMemory.test_avail_old_missing_fieldscsfdd}ttrdnd}tj|d|dN}tjdd}tj}WdQRX|j|j d|d }|j d t |j WdQRXdS)NcsF|dkrtjtjdjS|dkr2ttjdn|f||SdS)Nz /proc/meminfoaT Active: 9444728 kB Active(anon): 6145416 kB Active(file): 2950064 kB Buffers: 287952 kB Cached: 4818144 kB Inactive(file): 1578132 kB Inactive(anon): 574764 kB Inactive(file): 1567648 kB MemFree: 2057400 kB MemTotal: 16325648 kB Shmem: 577588 kB SReclaimable: 346648 kB z/proc/zoneinfozno such file or directory)rsrtrurvrwIOErrorerrnoENOENT)rxryrz)r{r-r.r|qs  zJTestSystemVirtualMemory.test_avail_old_missing_zoneinfo..open_mockz builtins.openz__builtin__.openT)r}r~)ridiiIrz,inactive memory stats couldn't be determinedi}l'Ll`LG) rrr rrrrZr[rrqrrr)r]r|rrrrrr-)r{r.test_avail_old_missing_zoneinfons  z7TestSystemVirtualMemory.test_avail_old_missing_zoneinfoN)rararb)__name__ __module__ __qualname__r`rskipIfrrXrrgrrhrjrlrnrprrrrrrrr-r-r-r.rYs$      ,"rYc@s\eZdZeddZddZeddZeddZd d Z d d Z d dZ ddZ dS)TestSystemSwapMemoryc Cs,td}|j}WdQRXd|ko*d|kS)z3Return True if /proc/meminfo provides swap metrics.z /proc/meminfoNz SwapTotal:z SwapFree:)rread)rdatar-r-r.meminfo_has_swap_infos z*TestSystemSwapMemory.meminfo_has_swap_infocCs"tj}tjj}|j||tdS)N)rc)rMrJrZ swap_memoryr\r )r]rfr_r-r-r.r`s zTestSystemSwapMemory.test_totalcCs"tj}tjj}|j||tdS)N)rc)rMrKrZrr\r )r]rfr_r-r-r.rgs zTestSystemSwapMemory.test_usedcCs"tj}tjj}|j||tdS)N)rc)rMr?rZrr\r )r]rfr_r-r-r.rhs zTestSystemSwapMemory.test_freecCstjdddv}tjdd^}tjdtj}|jt|d|d}|j dt |j |j|j d|j|j dWdQRXWdQRXdS) Nzpsutil._pslinux.openT)r})rrr7rz9'sin' and 'sout' swap memory stats couldn't be determined)r rrrrrZrrrrrrsinsout)r]rrrrr-r-r.test_missing_sin_souts  z*TestSystemSwapMemory.test_missing_sin_soutcsfdd}ttrdnd}tj|d|dv}tjdd^}tjdtj}|j t |d |d }|j d t |j |j |jd |j |jd WdQRXWdQRXdS) Ncs*|dkrttjdn|f||SdS)Nz /proc/vmstatzno such file or directory)rrr)rxryrz)r{r-r.r|sz=TestSystemSwapMemory.test_no_vmstat_mocked..open_mockz builtins.openz__builtin__.openT)r}r~)rrr7rzK'sin' and 'sout' swap memory stats couldn't be determined and were set to 0)rrr rrrrrZrrrrrrrr)r]r|rrrrrr-)r{r.test_no_vmstat_mockeds    z*TestSystemSwapMemory.test_no_vmstat_mockedcCs|jstjdStjd}tj}WdQRXddlj}|j \}}}}}}}||9}||9}|j |j ||j |j |dS)Nz!/proc/meminfo has no swap metricsz"psutil._pslinux.cext.linux_sysinfor) rrskipr rrZrZpsutil._psutil_linuxZ _psutil_linuxZ linux_sysinforrJr?)r]rswapZcextrIrJr?Zunit_multiplierr-r-r.test_meminfo_against_sysinfos   z1TestSystemSwapMemory.test_meminfo_against_sysinfoc sDfdd}ttrdnd}tj|d|d}tjWdQRXdS)Ncs&|dkrtjdS|f||SdS)Nz /proc/meminfo)rsrt)rxryrz)r{r-r.r|s zKTestSystemSwapMemory.test_emulate_meminfo_has_no_metrics..open_mockz builtins.openz__builtin__.openT)r}r~)rrr rrZr)r]r|rrr-)r{r.#test_emulate_meminfo_has_no_metricss   z8TestSystemSwapMemory.test_emulate_meminfo_has_no_metricsN) rrr staticmethodrr`rrgrhrrrrr-r-r-r.rs rc@s&eZdZejedddZejejj d dddZ ejejj d d d d Z eje d  d ddZ eje d dddZddZddZeje dddZejedeje dddZeje dddZeje dd d!Zejedeje dd"d#Zd$S)% TestSystemCPUzunknown failure on traviscCstjj}tjdtjdd}ttt |j d}|d krL|j d|n |j d||d krn|j d |n |j d ||dkr|j d |n |j d |dS)Nz \d+\.\d+\.\d+rrU ZstealrZguestraZ guest_nice)rrr)rrr)rarr) rZ cpu_times_fieldsrefindallosunamerVrWrDr@r assertNotIn)r]rZ kernel_verZkernel_ver_infor-r-r.test_cpu_timess   zTestSystemCPU.test_cpu_timesz/sys/devices/system/cpu/onlinez-/sys/devices/system/cpu/online does not existc CsVtd}|jj}WdQRXdt|krRt|jddd}|jtj|dS)Nz/sys/devices/system/cpu/online-r7) rrrRrrDr@rrZ cpu_count)r]rvaluer-r-r.*test_cpu_count_logical_w_sysdev_cpu_onlines   z8TestSystemCPU.test_cpu_count_logical_w_sysdev_cpu_onlinez/sys/devices/system/cpuz&/sys/devices/system/cpu does not existcCs0tjd}tdd|D}|jtj|dS)Nz/sys/devices/system/cpucSs g|]}tjd|dk r|qS)zcpu\d+$N)rsearch)r3r0r-r-r.r5%szITestSystemCPU.test_cpu_count_logical_w_sysdev_cpu_num..)rlistdirrrrZr)r]Zlscountr-r-r.'test_cpu_count_logical_w_sysdev_cpu_num!s z5TestSystemCPU.test_cpu_count_logical_w_sysdev_cpu_numZnprocznproc utility not availablecCs$ttd}|jtjdd|dS)Nz nproc --allT)logical)rDrrrZr)r]numr-r-r.test_cpu_count_logical_w_nproc(s z,TestSystemCPU.test_cpu_count_logical_w_nprocZlscpuzlscpu utility not availablecCs8td}tdd|jdD}|jtjdd|dS)Nzlscpu -pcSsg|]}|jds|qS)#)rA)r3r0r-r-r.r50sz@TestSystemCPU.test_cpu_count_logical_w_lscpu..r>T)r)rrr@rrZr)r]rFrr-r-r.test_cpu_count_logical_w_lscpu-sz,TestSystemCPU.test_cpu_count_logical_w_lscpuc &s2ddl}|jj}tjdtd}|j|jj|tjddd:}|j|jj|j|jd|j|j dddWdQRXt d d }|j }WdQRXt j |}tjd|dd }|j|jj|WdQRXfd d }t trdnd}tj||dd|j|jj|WdQRXWdQRXdS)Nrzpsutil._pslinux.os.sysconf)r~zpsutil._pslinux.openT)r}rz /proc/statz /proc/cpuinforb) return_valuer}cs(|jdrtjdS|f||SdS)Nz /proc/cpuinfor)rArsrt)rxryrz)r{r-r.r|Ps  z>TestSystemCPU.test_cpu_count_logical_mocked..open_mockz builtins.openz__builtin__.open)r~r})r_pslinuxZcpu_count_logicalr rrEr assertIsNoneZ call_count call_argsrrrsrtr) r]rZoriginalrrZ cpuinfo_data fake_filer|rr-)r{r.test_cpu_count_logical_mocked3s(       z+TestSystemCPU.test_cpu_count_logical_mockedc Cs.tjddd}|jtjjWdQRXdS)Nzpsutil._pslinux.openT)r})r rrrZrZcpu_count_physical)r]rr-r-r.test_cpu_count_physical_mocked[sz,TestSystemCPU.test_cpu_count_physical_mockedz not supportedc Cs,tjdgd|jtjWdQRXdS)Nzpsutil._pslinux.glob.glob)r)r rrrZcpu_freq)r]r-r-r.test_cpu_freq_no_resultbsz%TestSystemCPU.test_cpu_freq_no_resultzfails on Travisc sHfdd}gtjtjd|dd|jtdWdQRXdS)Ncs.|jdrjdgSjd|SdS)Nz&/sys/devices/system/cpu/cpufreq/policy)rAappend)pattern)flags orig_globr-r. glob_mockks    z>TestSystemCPU.test_cpu_freq_use_second_file..glob_mockzpsutil._pslinux.glob.globT)r~r}r)globr rrr)r]rr-)rrr.test_cpu_freq_use_second_filegs  z+TestSystemCPU.test_cpu_freq_use_second_filecsfdd}ttrdnd}tj||dTtjddgd8tj}|j|jd |j|jd |j|j d WdQRXWdQRXdS) NcsP|jdrtjdS|jdr(tjdS|jdr.open_mockz builtins.openz__builtin__.open)r~z glob.globz'/sys/devices/system/cpu/cpufreq/policy0)rg@@g@g@) rrr rrZrrcurrentminmax)r]r|rfreqr-)r{r.test_cpu_freq_emulate_datazs   z(TestSystemCPU.test_cpu_freq_emulate_datacsfdd}ttrdnd}dddg}tj||dRtjd |d 8tj}|j|jd |j|jd |j|j d WdQRXWdQRXdS)NcsP|jdrtjdS|jdr(tjdS|jdr.open_mockz builtins.openz__builtin__.openz'/sys/devices/system/cpu/cpufreq/policy0z'/sys/devices/system/cpu/cpufreq/policy1z'/sys/devices/system/cpu/cpufreq/policy2)r~z glob.glob)rgY@gi@gr@) rrr rrZrrrrr)r]r|rpoliciesrr-)r{r.test_cpu_freq_emulate_multi_cpus  z-TestSystemCPU.test_cpu_freq_emulate_multi_cpucsfdd}ttrdnd}dddg}tj||d6tjd |d tj}|j|jd WdQRXWdQRXfd d}ttrdnd}tj||d.tjd |d |jt tjWdQRXWdQRXdS) Ncs@|jdrttjdn$|jdr,tjdS|f||SdS)Nz/scaling_cur_freqr2z/cpuinfo_cur_freqs200000)rrrrrsrt)rxryrz)r{r-r.r|s    zGTestSystemCPU.test_cpu_freq_no_scaling_cur_freq_file..open_mockz builtins.openz__builtin__.openz'/sys/devices/system/cpu/cpufreq/policy0z'/sys/devices/system/cpu/cpufreq/policy1z'/sys/devices/system/cpu/cpufreq/policy2)r~z glob.glob)rcsD|jdrttjdn(|jdr0ttjdn|f||SdS)Nz/scaling_cur_freqr2z/cpuinfo_cur_freq)rrrr)rxryrz)r{r-r.r|s   ) rrr rrZrrr assertRaisesNotImplementedError)r]r|rrrr-)r{r.&test_cpu_freq_no_scaling_cur_freq_files   "  z4TestSystemCPU.test_cpu_freq_no_scaling_cur_freq_fileN)rrrrrrrrpathexistsrrrrrrrrrrrrrr-r-r-r.rs (  rc@s4eZdZejedddZejedddZdS)TestSystemCPUStatszfails on TraviscCs&td}tjj}|j||dddS)Nzcontext switchesi)rc)rTrZ cpu_statsZ ctx_switchesr\)r]r^r_r-r-r.test_ctx_switchess z$TestSystemCPUStats.test_ctx_switchescCs&td}tjj}|j||dddS)N interruptsi)rc)rTrZrrr\)r]r^r_r-r-r.test_interruptss z"TestSystemCPUStats.test_interruptsN)rrrrrrrrr-r-r-r.rsrc@s|eZdZddZddZeddZeje d deje d d d Z e j d ed e j dddddZddZdS)TestSystemNetworkcCsjxdtjjD]T\}}xJ|D]B}|jtjkr@|j|jt|q|jtj kr|j|jt |qWqWdS)N) rZ net_if_addrsitemsZfamilyZAF_LINKrZaddressr=r!r"r/)r]rxZaddrsZaddrr-r-r.test_net_if_addrs_ipss    z'TestSystemNetwork.test_net_if_addrs_ipscCsbx\tjjD]L\}}ytd|}Wntk r:YqX|j|jttj d|dqWdS)Nz ifconfig %sz(?i)MTU[: ](\d+)r) rZ net_if_statsrr RuntimeErrorrZmturDrr)r]rxstatsrFr-r-r.test_net_if_statssz#TestSystemNetwork.test_net_if_statscsfdd}tjddd}x|jD]\}y |}Wntk rNw$YnX|j|j|ddd |j|j|d dd |j|j|d dd |j|j|d dd |j|j |d dd |j|j |ddd |j|j |ddd |j|j |ddd q$WdS)Ncsi}td}ttjd|d|d<ttjd|d|d<ttjd|d|d<ttjd|d |d <ttjd |d|d <ttjd |d |d <ttjd|d|d<ttjd|d|d<|S)Nz ifconfig %szRX packets[: ](\d+)r packets_recvzTX packets[: ](\d+) packets_sentzerrors[: ](\d+)errinr7erroutzdropped[: ](\d+)dropindropoutz#RX (?:packets \d+ +)?bytes[: ](\d+) bytes_recvz#TX (?:packets \d+ +)?bytes[: ](\d+) bytes_sent)rrDrr)ZnicrrF)rxr-r.ifconfigs z8TestSystemNetwork.test_net_io_counters..ifconfigTF)ZpernicnowraprirN)rcrrrrrrrrii) rZnet_io_countersrrr\rrrrrrrr)r]rZniorZ ifconfig_retr-)rxr.test_net_io_counterss.  z&TestSystemNetwork.test_net_io_countersZipz'ip' utility not availablezskipped on TraviscCstdj}ddtjjD}d}xL|jdD]>}|j}tjd|r2|d7}|jddj}|j||q2W|j t ||d t j ||fd dS) Nzip addrcSsg|]}d|kr|qS):r-)r3r0r-r-r.r52sz7TestSystemNetwork.test_net_if_names..rr>z^\d+:r7rz %s --- %s)rd) rrRrZrkeysr@rrrrrpprintZpformat)r]rFZnicsfoundrHrxr-r-r.test_net_if_names.s  z#TestSystemNetwork.test_net_if_namesz psutil._pslinux.socket.inet_ntop)r~zpsutil._pslinux.supports_ipv6F)rc CsRy*tjtjtj}|j|j|jdWntjk r@YnXtjdddS)N::1rZinet6)kind)r r) r!ZAF_INET6Z SOCK_STREAM addCleanupcloseZbinderrorrZnet_connections)r]Z supports_ipv6Z inet_ntopr,r-r-r.%test_net_connections_ipv6_unsupported=s z7TestSystemNetwork.test_net_connections_ipv6_unsupportedc sFfdd}ttrdnd}tj||d}tjddWdQRXdS)Ncs,|dkrtjtjdS|f||SdS)Nz/proc/net/unixaB 0: 00000003 000 000 0001 03 462170 @/tmp/dbus-Qw2hMPIU3n 0: 00000003 000 000 0001 03 35010 @/tmp/dbus-tB2X8h69BQ 0: 00000003 000 000 0001 03 34424 @/tmp/dbus-cHy80Y8O 000000000000000000000000000000000000000000000000000000 )rsStringIOrurv)rxryrz)r{r-r.r|Jsz@TestSystemNetwork.test_net_connections_mocked..open_mockz builtins.openz__builtin__.open)r~Zunix)r)rrr rrZr)r]r|rrr-)r{r.test_net_connections_mockedIs    z-TestSystemNetwork.test_net_connections_mockedN)rrrrrrrrrrrr r rrErrr-r-r-r.rs  *  rc@sNeZdZejeed deddZddZ ddZ d d Z d d Z d S)TestSystemDisksstatvfszos.statvfs() not availablecCsdd}xtjddD]|}tj|j}||j\}}}}|j|j|t|j|d krl|jd|j|ft|j |d kr|jd|j |fqWdS) NcSsztd|j}|jd}|jd|jd}|jdd\}}}}|dkrRd}t|t|t|}}}||||fS)Nzdf -P -B 1 "%s"r>rZnoner2)rrRr@poprD)rrFrGrHdevrJrKr?r-r-r.dfis   z:TestSystemDisks.test_disk_partitions_and_usage..dfF)allrizpsutil=%s, df=%si(ii(i) rZdisk_partitionsZ disk_usageZ mountpointrrJrr?failrK)r]rpartZusagerrJrKr?r-r-r.test_disk_partitions_and_usageds  z.TestSystemDisks.test_disk_partitions_and_usagecCstdd}|j}WdQRXd|krPxtjD]}|jdkr0Pq0W|jdn`tjtd}t j d|dd<}t j d dgd  }tj}|j |djdWdQRXWdQRXdS)Nz/proc/filesystemsrzfszcouldn't find any ZFS partitionz nodev zfs zpsutil._pslinux.openT)rr}z$psutil._pslinux.cext.disk_partitions /dev/sdb3/rw)rr)r#r$r"r%) rrrZrZfstyperrsrrr rr)r]rrrrm1m2rr-r-r.test_disk_partitions_mocked~s     z+TestSystemDisks.test_disk_partitions_mockedc sfdd}ttrdnd}tj||d}tjdd}|j|jd|j|jd |j|j d t |j|j d |j|j d |j|j d |j|jdt |j|jd|j|jdWdQRXdS)NcsB|dkrtjtjdS|dkr.tjtdS|f||SdS)Nz/proc/partitionszu major minor #blocks name 8 0 488386584 hda z/proc/diskstatsz+ 3 0 1 hda 2 3 4 5 6 7 8 9 10 11 12)rsrrurvr)rxryrz)r{r-r.r|s zJTestSystemDisks.test_disk_io_counters_kernel_2_4_mocked..open_mockz builtins.openz__builtin__.open)r~F)rr7rrarrNrr)rrr rrZdisk_io_countersr read_countread_merged_count read_bytes SECTOR_SIZE read_time write_countwrite_merged_count write_bytes write_time busy_time)r]r|rrrr-)r{r.'test_disk_io_counters_kernel_2_4_mockeds   z7TestSystemDisks.test_disk_io_counters_kernel_2_4_mockedc sfdd}ttrdnd}tj||d}tjdd}|j|jd|j|jd |j|j d t |j|j d |j|j d |j|j d |j|jdt |j|jd|j|jdWdQRXdS)NcsB|dkrtjtjdS|dkr.tjtdS|f||SdS)Nz/proc/partitionszu major minor #blocks name 8 0 488386584 hda z/proc/diskstatsz' 3 0 hda 1 2 3 4 5 6 7 8 9 10 11)rsrrurvr)rxryrz)r{r-r.r|s zOTestSystemDisks.test_disk_io_counters_kernel_2_6_full_mocked..open_mockz builtins.openz__builtin__.open)r~F)rr7rrarrNrr)r*r)rrr rrZr+rr,r-r.r/r0r1r2r3r4r5)r]r|rrrr-)r{r.,test_disk_io_counters_kernel_2_6_full_mockeds   z.open_mockz builtins.openz__builtin__.open)r~F)rr7rrarr)rrr rrZr+rr,r.r/r1r3r-r0r2r4r5)r]r|rrrr-)r{r./test_disk_io_counters_kernel_2_6_limited_mockeds   z?TestSystemDisks.test_disk_io_counters_kernel_2_6_limited_mockedN) rrrrrhasattrrrr r(r6r7r8r-r-r-r.ras  rc@sVeZdZddZejdddZddZdd Zd d Z d d Z ddZ ddZ dS)TestMisccCs(td}tj}|jt|t|dS)Nz boot time)rTrZ boot_timerrD)r]r^r_r-r-r.test_boot_timeszTestMisc.test_boot_timezpsutil.traceback.print_excc"stj}ttjj|dd$}|jd|jd|jdWdQRXztfdd}trbdnd }tj ||d nt t |j t t j|j t t jd d |j t t j|j t t jd d |j t t j|j t t jd d |t _|jt jd |jtt jd t jd d }|jt|d t jd d }|jttt|d ttjj|dd$}|jd|jd|jdWdQRX|jt jd |jtt jd d d |jtt jd |jtttt jd d d WdQRXWdtj|t t X|jt jddS)NrSrzcpu 0 0 0 0 0 0 0 0 0 0 zcpu0 0 0 0 0 0 0 0 0 0 0 zcpu1 0 0 0 0 0 0 0 0 0 0 cs&|jdrttjd|f||S)Nz/proczrejecting access for test)rArrr)rxryrz)r{r-r.r|s  z4TestMisc.test_no_procfs_on_import..open_mockz builtins.openz__builtin__.open)r~T)percpurzcpu 1 0 0 0 0 0 0 0 0 0 zcpu0 1 0 0 0 0 0 0 0 0 0 zcpu1 1 0 0 0 0 0 0 0 0 0 z/proc)tempfilemkdtemprrrr;writerr rrrZrrrZ cpu_percentZcpu_times_percent PROCFS_PATHrsumrWZassertNotEqualshutilZrmtree)r]tbZ my_procfsrr|rZper_cpu_percentZper_cpu_times_percentr-)r{r.test_no_procfs_on_importsL        (  z!TestMisc.test_no_procfs_on_importc Cs.tjddd}|jttjjWdQRXdS)Nzpsutil._pslinux.openT)r})r rrrrZrr;)r]rr-r-r.test_boot_time_mockedDs  zTestMisc.test_boot_time_mockedcCstjdd gd}|jtjd jd WdQRXtjddgd}|jtjd jd WdQRXtjddgd}|jtjd jd WdQRXdS)Nzpsutil._pslinux.cext.users giampaolopts/2:0hATr)rrZ localhost:0.0foo)rGrHrIrJTr)rGrHrKrJTr)rGrHrLrJTr)r rrrZZusershost)r]rr-r-r.test_users_mockedKs     zTestMisc.test_users_mockedc Cstj}z|t_|jttj|jttj|jttjdd|jttj|jttj |jttj |jttj |jttj |jttj |jtjtjWddt_tj|XdS)NT)r=z/proc)r>r?rZrArrr[rr;rrrr+rZ NoSuchProcessProcessrrmdir)r]Ztdirr-r-r.test_procfs_path_szTestMisc.test_procfs_pathc sHfdd}gttrdnd}tj||dtjWdQRXdS)NcsJtrt|tr|j}d|kr6jdttjdn|f||SdS)NZhw_sector_sizer2)r isinstancer decoderrrr)rxryrz)flagr{r-r.r|us  z1TestMisc.test_sector_size_mock..open_mockz builtins.openz__builtin__.open)r~)rrr rrZr+)r]r|rr-)rTr{r.test_sector_size_mockrs  zTestMisc.test_sector_size_mockc CsZt}|jz.open_mockz builtins.openz__builtin__.open)r~)rrr r)r]r|rr-)r{r.test_pid_exists_no_proc_statuss   z'TestMisc.test_pid_exists_no_proc_statusN) rrrr<r rrErFrNrQrUr]r_r-r-r-r.r:s>r:z no batteryc@seZdZejed dddZejed dddZddZd d Z d d Z d dZ ddZ ddZ ddZddZddZddZdS)TestSensorsBatteryZacpizacpi utility not availablecCsDtd}t|jddjjdd}tjj}|j||dddS)Nzacpi -b,r7%r2)rc) rrDr@rRreplacerZsensors_batterypercentr\)r]rFZ acpi_valuer_r-r-r. test_percents zTestSensorsBattery.test_percentcCsTtd}d|jkrtjdSd|kr,d}nd|jddk}|jtjj|dS) Nzacpi -bunknownzacpi output not reliablezdischarging at zero rateTZChargingr>r) rlowerrrr@rrZrd power_plugged)r]rFZpluggedr-r-r.test_power_pluggeds  z%TestSensorsBattery.test_power_pluggedc s`fdd}ttrdnd}tj||d,}|jtjjd|jtjjtj WdQRXdS)Ncs2|jds|jdrtjdS|f||SdS)Nz AC0/onlinez AC/online1)rrsrt)rxryrz)r{r-r.r|s z@TestSensorsBattery.test_emulate_power_plugged..open_mockz builtins.openz__builtin__.open)r~T) rrr rrrZrdriZsecsleftZPOWER_TIME_UNLIMITED)r]r|rrr-)r{r.test_emulate_power_pluggeds  z-TestSensorsBattery.test_emulate_power_pluggedc sLfdd}ttrdnd}tj||d}|jtjjdWdQRXdS)NcsN|jds|jdr"ttjdn(|jdr:tjtdS|f||SdS)Nz AC0/onlinez AC/onliner2z/statusZcharging)rrrrrsrr)rxryrz)r{r-r.r|s  zBTestSensorsBattery.test_emulate_power_plugged_2..open_mockz builtins.openz__builtin__.open)r~T)rrr rrrZrdri)r]r|rrr-)r{r.test_emulate_power_plugged_2s   z/TestSensorsBattery.test_emulate_power_plugged_2c sLfdd}ttrdnd}tj||d}|jtjjdWdQRXdS)Ncs2|jds|jdrtjdS|f||SdS)Nz AC0/onlinez AC/online0)rrsrt)rxryrz)r{r-r.r|s zDTestSensorsBattery.test_emulate_power_not_plugged..open_mockz builtins.openz__builtin__.open)r~F)rrr rrrZrdri)r]r|rrr-)r{r.test_emulate_power_not_pluggeds   z1TestSensorsBattery.test_emulate_power_not_pluggedc sLfdd}ttrdnd}tj||d}|jtjjdWdQRXdS)NcsN|jds|jdr"ttjdn(|jdr:tjtdS|f||SdS)Nz AC0/onlinez AC/onliner2z/statusZ discharging)rrrrrsrr)rxryrz)r{r-r.r|s  zFTestSensorsBattery.test_emulate_power_not_plugged_2..open_mockz builtins.openz__builtin__.open)r~F)rrr rrrZrdri)r]r|rrr-)r{r. test_emulate_power_not_plugged_2s   z3TestSensorsBattery.test_emulate_power_not_plugged_2c sJfdd}ttrdnd}tj||d}|jtjjWdQRXdS)NcsJ|jds|jdr"ttjdn$|jdr6tjdS|f||SdS)Nz"/sys/class/power_supply/AC0/onlinez!/sys/class/power_supply/AC/onliner2z#/sys/class/power_supply/BAT0/statuss???)rArrrrsrt)rxryrz)r{r-r.r|s     zETestSensorsBattery.test_emulate_power_undetermined..open_mockz builtins.openz__builtin__.open)r~)rrr rrrZrdri)r]r|rrr-)r{r.test_emulate_power_undetermineds   z2TestSensorsBattery.test_emulate_power_undeterminedc sHfdd}ttrdnd}tj||d}|jtjWdQRXdS)Ncs6|jds|jdr"ttjdn|f||SdS)Nz'/sys/class/power_supply/BAT0/energy_nowz'/sys/class/power_supply/BAT0/charge_nowr2)rArrr)rxryrz)r{r-r.r|s  z@TestSensorsBattery.test_emulate_no_base_files..open_mockz builtins.openz__builtin__.open)r~)rrr rrrZrd)r]r|rrr-)r{r.test_emulate_no_base_filess   z-TestSensorsBattery.test_emulate_no_base_filesc sLfdd}ttrdnd}tj||d}|jtjjdWdQRXdS)Ncs(|jdrtjdS|f||SdS)Nz(/sys/class/power_supply/BAT0/energy_fullrn)rArsrt)rxryrz)r{r-r.r|&s  z@TestSensorsBattery.test_emulate_energy_full_0..open_mockz builtins.openz__builtin__.open)r~r)rrr rrrZrdre)r]r|rrr-)r{r.test_emulate_energy_full_0$s   z-TestSensorsBattery.test_emulate_energy_full_0c sLfdd}ttrdnd}tj||d}|jtjjdWdQRXdS)NcsRd}d}|j|s|j|r*ttjdn$|jdr>tjdS|f||SdS)Nz(/sys/class/power_supply/BAT0/energy_fullz(/sys/class/power_supply/BAT0/charge_fullr2z%/sys/class/power_supply/BAT0/capacitys88)rArrrrsrt)rxryrzZ energy_fullZ charge_full)r{r-r.r|5s  zHTestSensorsBattery.test_emulate_energy_full_not_avail..open_mockz builtins.openz__builtin__.open)r~X)rrr rrrZrdre)r]r|rrr-)r{r."test_emulate_energy_full_not_avail2s   z5TestSensorsBattery.test_emulate_energy_full_not_availc s:fdd}tjjtjd|d}tjWdQRXdS)Ncs|jdrdS|SdS)Nz"/sys/class/power_supply/AC0/onlineF)rA)rx)orig_path_existsr-r.path_exists_mockGs zGTestSensorsBattery.test_emulate_no_ac0_online..path_exists_mockzpsutil._pslinux.os.path.exists)r~)rrrr rrZrd)r]rwrr-)rvr.test_emulate_no_ac0_onlineEs   z-TestSensorsBattery.test_emulate_no_ac0_onlinec sJfdd}ttrdnd}tj||d}|jtjjWdQRXdS)Ncs@|jds|jds|jdr,ttjdn|f||SdS)Nz!/sys/class/power_supply/AC/onlinez"/sys/class/power_supply/AC0/onlinez#/sys/class/power_supply/BAT0/statusr2)rArrr)rxryrz)r{r-r.r|Us    z;TestSensorsBattery.test_emulate_no_power..open_mockz builtins.openz__builtin__.open)r~)rrr rrrZrdri)r]r|rrr-)r{r.test_emulate_no_powerSs   z(TestSensorsBattery.test_emulate_no_powerN)rrrrrrrfrjrlrmrorprqrrrsrurxryr-r-r-r.r`s r`c@s(eZdZejedddZddZdS)TestSensorsTemperatureszunreliable on TRAVIScsxfdd}ttrdnd}tj||dD}tjdd,}|jtji|j dt |d j WdQRXWdQRXdS) Ncs,|jdrttjdn|f||SdS)NZ_inputr2)rOSErrorrZEIO)rxryrz)r{r-r.r|is zATestSensorsTemperatures.test_emulate_eio_error..open_mockz builtins.openz__builtin__.open)r~T)rZignoringr) rrr rrrrrZsensors_temperaturesrrr)r]r|rrrr-)r{r.test_emulate_eio_errorgs  z.TestSensorsTemperatures.test_emulate_eio_errorcsfdd}ttrdnd}tj||djtjddgdNtjd d }|j|jd |j|jd |j|j d |j|j dWdQRXWdQRXdS)Ncs|jdrtjtdS|jdr0tjtdS|jdrDtjdS|jdrXtjdS|jd rltjd S|f||SdS) Nz/namerxz /temp1_labellabelz /temp1_inputs30000z /temp1_maxs40000z /temp1_crits50000)rrsrrrt)rxryrz)r{r-r.r|xs        z.open_mockz builtins.openz__builtin__.open)r~z glob.globz/sys/class/hwmon/hwmon0/temp1)rrxrr~g>@gD@gI@) rrr rrZr|rr~rZhighZcritical)r]r|rZtempr-)r{r.test_emulate_dataws   z)TestSensorsTemperatures.test_emulate_dataN)rrrrrrr}rr-r-r-r.rzdsrzc@seZdZddZdS)TestSensorsFanscsfdd}ttrdnd}tj||dNtjddgd2tjd d }|j|jd |j|jd WdQRXWdQRXdS) Ncs\|jdrtjtdS|jdr0tjtdS|jdrHtjtdS|f||SdS)Nz/namerxz /fan1_labelr~z /fan1_inputZ2000)rrsrr)rxryrz)r{r-r.r|s   z4TestSensorsFans.test_emulate_data..open_mockz builtins.openz__builtin__.open)r~z glob.globz/sys/class/hwmon/hwmon2/fan1)rrxrr~i) rrr rrZZ sensors_fansrr~r)r]r|rZfanr-)r{r.rs   z!TestSensorsFans.test_emulate_dataN)rrrrr-r-r-r.rsrc@seZdZddZeZddZejedddZ dd Z d d Z d d Z ddZ ddZddZddZddZddZeje dddZddZdd Zd!d"Zd#S)$ TestProcesscCs ttdS)N)rr)r]r-r-r.setUpszTestProcess.setUpcCstjdt}t|}|jttdddttj|j }t j d|j }|j dd}|j|jtdd |Dd d |j|jtd d |Dd d |j|jtd d |Dd d dS)Nzk import time with open("%s", "w") as f: time.sleep(10) cSs tjdS)NrU)rrr-r-r-r.sz3TestProcess.test_memory_full_info..z'%s' not in retg?F)ZgroupedcSsg|]}|j|jqSr-)Z private_dirtyZ private_clean)r3r0r-r-r.r5sz5TestProcess.test_memory_full_info..i)rccSsg|] }|jqSr-)pss)r3r0r-r-r.r5scSsg|] }|jqSr-)r)r3r0r-r-r.r5s)rurvrr rrrrZrOpidtimeZsleepZmemory_full_info memory_mapsr\ZussrBrr)r]srcZsprocr[Zmemmapsr-r-r.test_memory_full_infos      z!TestProcess.test_memory_full_infozunreliable on PYPYc;CsRdd}ttd|j|jdWdQRXttd|j|jdWdQRXttd|j|jdWdQRXttd|j|jdWdQRXttd|j|jdWdQRXttd|j|jdWdQRXtrNttttd |j|jdWdQRXttttd |j|jdWdQRXdS) NcSs\tj}tjd}x:x4|jD](}|jtjjtkr:|Stj|kr Pq WqWtddS)Nrztimeout looking for test file) rZrOr open_filesrrabspathrr)r[Z giveup_atfiler-r-r. get_test_files   z7TestProcess.test_open_files_mode..get_test_filerr!rzr+zw+za+r0zx+)rrrmoderr)r]rr-r-r.test_open_files_modes(        z TestProcess.test_open_files_modecCstj}|j}tjvt|jdt|tjdt t j dd}|j}WdQRXtjdt t j dd}|j |jgWdQRXWdQRXdS)Nzlen(ret) != %izpsutil._pslinux.os.readlinkr2)r~)rZrOrr>NamedTemporaryFilerrr rr{rrZEINVALr)r]r[filesrr-r-r.test_open_files_file_gones  z%TestProcess.test_open_files_file_gonecCsrtj}|j}tjPt|jdt|tr6dnd}tj |t t j dd}|j}WdQRXWdQRXdS)Nzlen(ret) != %iz builtins.openz__builtin__.openr2)r~) rZrOrr>rrrrr rrrr)r]r[rrrr-r-r.test_open_files_fd_gones  z#TestProcess.test_open_files_fd_gonec Cs8tjdid }|jtjjtjjWdQRXdS)Nz)psutil._pslinux._psposix.get_terminal_map)r) r rrrZrrOrr^Zterminal)r]rr-r-r.test_terminal_mockeds z TestProcess.test_terminal_mockedcCstj}tjtd}tjd|dd}|j|jddgWdQRXtjtd}tjd|dd}|j|jdddgWdQRXdS) Nzfoobarzpsutil._pslinux.openT)rr}rLbarz foobarr2) rZrOrsrrr rrcmdline)r]r[rrr-r-r.test_cmdline_mocked%s   zTestProcess.test_cmdline_mockedcCstj}tjtd}tjd|dd}|j|jddgWdQRXtjtd}tjd|dd}|j|jdddgWdQRXdS) Nzfoo bar zpsutil._pslinux.openT)rr}rLrz foo bar r2) rZrOrsrrr rrr)r]r[rrr-r-r.test_cmdline_spaces_mocked3s   z&TestProcess.test_cmdline_spaces_mockedc CsFtjddd.|jtjjd|jtjjdWdQRXdS)Nzpsutil._pslinux.os.readlinkz/home/foo (deleted))rz /home/foo)r rrrZrOexecwd)r]r-r-r.!test_readlink_path_deleted_mockedAs z-TestProcess.test_readlink_path_deleted_mockedcsfdd}ttrdnd}tj||d}tjj}|j|gWdQRXfdd}tj||d|jtj tjjWdQRXdS)Ncs4|jdtjr ttjdn|f||SdS)Nz /proc/%s/taskr2)rArr^rrr)rxryrz)r{r-r.r|Lsz2TestProcess.test_threads_mocked..open_mockz builtins.openz__builtin__.open)r~cs4|jdtjr ttjdn|f||SdS)Nz /proc/%s/taskr2)rArr^rrZEPERM)rxryrz)r{r-r.r|[s) rrr rrZrOrWrr AccessDenied)r]r|rrrr-)r{r.test_threads_mockedGs    zTestProcess.test_threads_mockedcCstjdttjddn}tjdtjdddL}tjj}|j |dtjddd|j tj tjjWdQRXWdQRXWdQRXdS) Nzpsutil._pslinux.readlinkr2)r~zpsutil.Process.cmdlinerzpsutil._pslinux.os.path.lexistsF)r) r rr{rrrZrrOrrr ZombieProcess)r]r&r'rr-r-r.test_exe_mockedds   zTestProcess.test_exe_mockedcsrfdd}ttrdnd}tj||d>}tj}|jt}|jWdQRX|j |j j t j WdQRXdS)Ncs4|jdtjr ttjdn|f||SdS)Nz/proc/%s/smapsr2)rArr^rrr)rxryrz)r{r-r.r||sz.TestProcess.test_issue_1014..open_mockz builtins.openz__builtin__.open)r~) rrr rrZrOrrrr exceptionrr)r]r|rrr[errr-)r{r.test_issue_1014ys   zTestProcess.test_issue_1014z not supportedcCstjdttjdd:}tj}|j|jtj }|j tj WdQRXWdQRX|j |j j|j|j |j j|jdS)Nz"psutil._pslinux.cext.linux_prlimitr2)r~)r rr{rZENOSYSrZrOrxrrZrlimitZ RLIMIT_NOFILErrr)r]rr[excr-r-r.test_rlimit_zombies zTestProcess.test_rlimit_zombiecCs|tjdttjdd6}tj}|j|jtj }|j WdQRXWdQRX|j |j j |j |j |j j|jdS)Nzpsutil._pslinux.os.readlinkr2)r~)r rr{rrrZrOrxrrrrrr)r]rr[rr-r-r.test_cwd_zombies zTestProcess.test_cwd_zombiec sddlm}fdd}ttr$dnd}tj||dtj}|j|j d|j|j tj |j|j d |j|j d |tj|j}|j|jd ||j|jd ||j|jd ||j|jd||j|jd WdQRXdS)Nr) CLOCK_TICKSc's|jdtjrxddddddddddddddddd ddddd ddddddddddddddddd g'}tjd j|jS|f||SdS) Nz /proc/%s/stat0z(cat)Z123456rQ)rArr^rsrtr;rw)rxryrz)r{r-r.r|sTz5TestProcess.test_stat_file_parsing..open_mockz builtins.openz__builtin__.open)r~catr7rrrarrN)rrrrr rrZrOrrxstatusZ STATUS_ZOMBIEppidZ create_timer;rusersystem children_userchildren_systemZcpu_num)r]rr|rr[Zcpur-)r{r.test_stat_file_parsings"  / z"TestProcess.test_stat_file_parsingc sfdd}ttrdnd}tj||dtj}|j|jjd|j|jj d|j|j d|j }|j|j d |j|j d |j|jd |j}|j|j d |j|j d |j|jd|j|jjttddWdQRXdS)Ncs:|jdtjr&tjtjdjS|f||SdS)Nz/proc/%s/statusa+ Uid: 1000 1001 1002 1003 Gid: 1004 1005 1006 1007 Threads: 66 Cpus_allowed: f Cpus_allowed_list: 0-7 voluntary_ctxt_switches: 12 nonvoluntary_ctxt_switches: 13)rArr^rsrtrurvrw)rxryrz)r{r-r.r|s z7TestProcess.test_status_file_parsing..open_mockz builtins.openz__builtin__.open)r~rb Biiiiiirr*)rrr rrZrOrnum_ctx_switches voluntary involuntary num_threadsuidsrealZ effectiveZsavedgids_proc_get_eligible_cpuslistrange)r]r|rr[rrr-)r{r.test_status_file_parsings"  z$TestProcess.test_status_file_parsingN)rrrrZtearDownrrrr rrrrrrrrrrr rrrrr-r-r-r.rs"$ Brc@sreZdZdZeddZddZddZdd Zd d Z d d Z ddZ ddZ e ddZddZddZdS)TestProcessAgainstStatusa /proc/pid/stat and /proc/pid/status have many values in common. Whenever possible, psutil uses /proc/pid/stat (it's faster). For all those cases we check that the value found in /proc/pid/stat (by psutil) matches the one found in /proc/pid/status. cCstj|_dS)N)rZrOproc)clsr-r-r. setUpClasssz#TestProcessAgainstStatus.setUpClasscCs|tjjd|jj^}xJ|D]B}|j}|j|r|jdd}yt|St k r\|SXqWt d|WdQRXdS)Nz/proc/%s/status rz can't find %r) rZ _psplatform open_textrrrRrA partitionrDrE)r]Z linestartrrHrr-r-r.read_status_files   z)TestProcessAgainstStatus.read_status_filecCs |jd}|j|jj|dS)NzName:)rrrrx)r]rr-r-r. test_name!s z"TestProcessAgainstStatus.test_namecCsH|jd}||jdd|jd}|jdd}|j|jj|dS)NzState:(r7)rQr)rfindrfindrcrrr)r]rr-r-r. test_status%s  z$TestProcessAgainstStatus.test_statuscCs |jd}|j|jj|dS)NzPPid:)rrrr)r]rr-r-r. test_ppid+s z"TestProcessAgainstStatus.test_ppidcCs |jd}|j|jj|dS)NzThreads:)rrrr)r]rr-r-r.test_num_threads/s z)TestProcessAgainstStatus.test_num_threadscCs:|jd}ttt|jdd}|j|jj|dS)NzUid:r7r)rrVrWrDr@rrr)r]rr-r-r. test_uids3s z"TestProcessAgainstStatus.test_uidscCs:|jd}ttt|jdd}|j|jj|dS)NzGid:r7r)rrVrWrDr@rrr)r]rr-r-r. test_gids8s z"TestProcessAgainstStatus.test_gidscCs@|jd}|j|jjj||jd}|j|jjj|dS)Nzvoluntary_ctxt_switches:znonvoluntary_ctxt_switches:)rrrrrr)r]rr-r-r.test_num_ctx_switches=s  z.TestProcessAgainstStatus.test_num_ctx_switchescCsN|jd}dt|krJtt|jd\}}|j|jjtt ||ddS)NzCpus_allowed_list:rr7) rrrWrDr@rrZ cpu_affinityrr)r]rZmin_Zmax_r-r-r.test_cpu_affinityDs   z*TestProcessAgainstStatus.test_cpu_affinityc Cs>|jd}tjd}|jjjWdQRXdt|kr:ndS)NzCpus_allowed_list:zpsutil._pslinux.per_cpu_timesr)rr rrrrr)r]rrr-r-r.test_cpu_affinity_eligible_cpusKs    z8TestProcessAgainstStatus.test_cpu_affinity_eligible_cpusN)rrr__doc__ classmethodrrrrrrrrrrrrr-r-r-r.rs  rc@s,eZdZddZddZddZddZd S) TestUtilsc Cs*tjjt}|j|jdWdQRXdS)NZrt)rZrr__file__rr)r]rr-r-r.test_open_text]szTestUtils.test_open_textc Cs*tjjt}|j|jdWdQRXdS)Nr)rZrrrrr)r]rr-r-r.test_open_binaryaszTestUtils.test_open_binaryc Cs2tjddd}|jtjjddWdQRXdS)Nz os.readlinkz foo (deleted))rrrL)r rrrZrreadlink)r]rr-r-r. test_readlinkeszTestUtils.test_readlinkc Cs|tjjt}t|d}|jdWdQRX|jtjj tddd|jtjj tddd|jtjj tdd d d dS) NZwtzfoo F)ZbinaryrLTsfooz??r)Zfallback) rrrrrr@rrZrr)r]Zfnamerr-r-r.test_catjs  zTestUtils.test_catN)rrrrrrrr-r-r-r.rZsr__main__)KrZ __future__rrBr$rrrsrr rrCr!r)r>rurrrZrZpsutil._compatrrZ psutil.testsrrrr r r r r rrrrrrrrrrrrrrdirnamerZHEREr(Z SIOCGIFCONFr9r/r/r=rMrPrTrXrZTestCaserYrrrrrr:r`rzrrrrrr-r-r-r.s                             k T  t  .  7 -  Y R  PK!V% #__pycache__/test_aix.cpython-36.pycnu[3 JZm@sxdZddlZddlmZddlmZddlmZddlmZddlZeje dGdd d ej Z e d krtee dS) zAIX specific tests.N)AIX)run_test_module_by_name)sh)unittestzAIX onlyc@s4eZdZddZddZddZddZd d Zd S) AIXSpecificTestCasec Cstd}d}xdjD]}|d|f7}qWtj||}|j|dd}t|jd|}t|jd|}t|jd |}t|jd |} tj} d ||} |j | j ||j | j || d |j | j || d |j | j| | d dS) Nz/usr/bin/svmon -O unit=KBz memory\s*z+size inuse free pin virtual available mmodez(?P<%s>\S+)\s+z(svmon command returned unexpected outputisize availableZinusefree)delta)rsplitresearchassertIsNotNoneintgrouppsutilZvirtual_memory assertEqualtotalassertAlmostEqualusedrr ) selfout re_patternfieldmatchobjZKBrrrr psutil_resultZMEMORY_TOLERANCEr /usr/lib64/python3.6/test_aix.pytest_virtual_memorys*  z'AIXSpecificTestCase.test_virtual_memorycCsTtd}tjd|}|j|dt|jd}d}tj}|jt|j ||dS)Nz/usr/sbin/lsps -az=(?P\S+)\s+(?P\S+)\s+(?P\S+)\s+(?P\d+)MBz'lsps command returned unexpected outputrir i) rr rrrrrZ swap_memoryrr)rrrZtotal_mbZMBrrrrtest_swap_memory4sz$AIXSpecificTestCase.test_swap_memorycCstd}d}xdjD]}|d|f7}qWtj||}|j|dd}tj}|j|jt |j d|d|j|j t |j d |d|j|j t |j d |d|j|j t |j d |ddS) Nz/usr/bin/mpstat -azALL\s*zfmin maj mpcs mpcr dev soft dec ph cs ics bound rq push S3pull S3grd S0rd S1rd S2rd S3rd S4rd S5rd syscz(?P<%s>\S+)\s+z)mpstat command returned unexpected outputiZcs)r ZsyscZdevZsoft)rr r rrrZ cpu_statsrZ ctx_switchesrrZsyscallsZ interruptsZsoft_interrupts)rrrrrZCPU_STATS_TOLERANCErrrrtest_cpu_statsIs2     z"AIXSpecificTestCase.test_cpu_statscCs:td}ttjd|jd}tjdd}|j||dS)Nz/usr/bin/mpstat -az lcpu=(\d+)T)Zlogical)rrr rrr cpu_countr)rrZ mpstat_lcpuZ psutil_lcpurrrtest_cpu_count_logicaljs z*AIXSpecificTestCase.test_cpu_count_logicalcCs4td}t|j}ttjj}|j||dS)Nz/etc/ifconfig -l)rsetr rZ net_if_addrskeysZassertSetEqual)rrZifconfig_namesZ psutil_namesrrrtest_net_if_addrs_namesps z+AIXSpecificTestCase.test_net_if_addrs_namesN)__name__ __module__ __qualname__rr r!r$r'rrrrrs !r__main__) __doc__r rrZ psutil.testsrrrZskipIfZTestCaserr(__file__rrrrs     cPK!Z$d?d@Z%dAdBZ&dCdDZ'dEdFZ(dGdHZ)e j e*dIdJdKZ+e j e,o\e-j.j/dL dMe j e0ote1j2dNkdOdPdQZ3dRdSZ4e j e0pe*oe1j5 dTdUdVZ6dWdXZ7e j e8 dYdZd[Z9d\d]Z:e j e; d^d_d`Z d^e j e? dcdddeZ@e j eA d^dfdgZBdNS)hTestSystemAPIszTests for system-related APIs.cCs ttdS)N)rr)selfr##/usr/lib64/python3.6/test_system.pysetUp>szTestSystemAPIs.setUpcCs tdS)N)r)r"r#r#r$tearDownAszTestSystemAPIs.tearDowncCs|jtjddtjDt}|j|jddtjDtj|j}|j|j |j |jddtjDt j dtj tjd|jttjgWdQRXt j dtjtjd*|jtjttjWdQRXWdQRXdS)NcSsg|] }|jqSr#)pid).0xr#r#r$ Esz4TestSystemAPIs.test_process_iter..cSsg|] }|jqSr#)r')r(r)r#r#r$r*GscSsg|] }|jqSr#)r')r(r)r#r#r$r*Kszpsutil.Process) side_effect)assertInosgetpidpsutil process_iterrr'Processkillwait assertNotInrpatchZ NoSuchProcess assertEquallist AccessDenied assertRaises)r"sprocpr#r#r$test_process_iterDs z TestSystemAPIs.test_process_itercCs8x.tjdgdD]}|jt|jjdgqW|jtttjdgdWdQRXtj dtj dddL}x:tjddgdD]&}|j |jd|j |jddqW|j stWdQRXtj dtj dddX}t}x>tjddg|d D](}|j|jd||j |jddqW|j s*tWdQRXdS) Nr')attrsZfooz$psutil._psplatform.Process.cpu_timesr)r+ cpu_times)r=Zad_value)r/r0r6r7infokeysr9 ValueErrorrr5r8 assertIsNoneassertGreaterEqualcalledAssertionErrorobjectassertIs)r"r;mflagr#r#r$test_prcess_iter_w_paramsUs$ z(TestSystemAPIs.test_prcess_iter_w_paramsc sfdd}gt}t}t}dd|||fD}jttj|ddjttj|ddtj}tj|d|d \}}jtj|d j|gjt |d jgx|D]} j t | d qWt d fdd} |j | ||\}}j|jdd|Dtr4j|jjtj nj|jjdj|jgx|D]} j t | d q\Wt d fdd} |j |j | ||\}}jtt|j|j|jgx|D]} jt | d qWdS)Ncsj|jdS)N)appendr')r;)pidsr#r$callbackjsz0TestSystemAPIs.test_wait_procs..callbackcSsg|]}tj|jqSr#)r/r1r')r(r)r#r#r$r*qsz2TestSystemAPIs.test_wait_procs..)timeout)rNg{Gz?)rPrNg? returncodecs<tj|d|d\}}jt|djt|d||fS)NgQ?)rPrNrO)r/ wait_procsr6len)procsrNgonealive)r"r#r$test~s  z,TestSystemAPIs.test_wait_procs..testcSsg|] }|jqSr#)r')r(r)r#r#r$r*scs<tj|d|d\}}jt|djt|d||fS)NgQ?)rPrNrQr)r/rUr6rV)rWrNrXrY)r"r#r$rZs  )rr9rBr/rU TypeErrortime assertLessr6rV assertFalsehasattrr terminater,r'r poprRsignalSIGTERMset assertTrue) r"rNsproc1sproc2sproc3rWtrXrYr;rZr#)rMr"r$test_wait_procsisB       zTestSystemAPIs.test_wait_procscCsNt}t}t}dd|||fD}x|D] }|jq,Wtj|\}}dS)NcSsg|]}tj|jqSr#)r/r1r')r(r)r#r#r$r*sz=TestSystemAPIs.test_wait_procs_no_timeout..)rrar/rU)r"rgrhrirWr;rXrYr#r#r$test_wait_procs_no_timeouts  z)TestSystemAPIs.test_wait_procs_no_timeoutcCs4tj}|j|t|j|d|j|tjdS)Nr)r/Z boot_timeassertIsInstancefloat assertGreaterr^r])r"Zbtr#r#r$test_boot_times  zTestSystemAPIs.test_boot_timez POSIX onlycCs"ddl}|jtjd|jdS)Nr SC_PAGE_SIZE)resourcer6r-sysconfZ getpagesize)r"rrr#r#r$ test_PAGESIZEszTestSystemAPIs.test_PAGESIZEcCstj}|jdkst||jdks,t|d|jko@dknsNt||jdks`t||jdksrt|xt|jD]j}t ||}|dkr|j |t t f|dkrz|dks|j d||f||jkrz|j d||j||fqzWdS)Nrdpercenttotalz %r < 0 (%s)z%r > total (total=%s, %s=%s))r/Zvirtual_memoryrwrFZ availablervusedfree_fieldsgetattrrmintr fail)r"memnamevaluer#r#r$test_virtual_memorys "   z"TestSystemAPIs.test_virtual_memorycCstj}|j|jd |jdks(t||jdks:t||jdkrX|jdksjt|n|jdksjt|d|jko~dknst||j dkst||j dkst|dS) Nrwrxryrvsinsoutrru)rwrxryrvrr) r/Z swap_memoryr6rzrwrFrxryrvrr)r"r~r#r#r$test_swap_memorys  "zTestSystemAPIs.test_swap_memorycCstt}|jtj|jtj|j}|j|j|jtj|j|jtjd|j tjddtj kdS)NrOrr[) rrfr/ pid_existsr'r1r2r3r_r6rM)r"r:r;r#r#r$test_pid_existss zTestSystemAPIs.test_pid_existsc Csttj}xT|D]L}ytj|s(tWqtk r^tjd|tjkrZ|j|YqXqWtt |dt |d}x |D]}|j tj||dqWdS)Ng?iip)msg) rr/rMrrFr]sleepr}rangemaxr_)r"rMr'r#r#r$test_pid_exists_2s    z TestSystemAPIs.test_pid_exists_2cCsJddtjD}tj}|j|j|j|jt|tt|dS)NcSsg|] }|jqSr#)r')r(r)r#r#r$r*sz,TestSystemAPIs.test_pids..)r/r0rMr6sortrVre)r"ZplistZpidlistr#r#r$ test_pidsszTestSystemAPIs.test_pidsc Cs&tj}tt_z tjWd|t_XdS)N)sysstdoutrr/rZ)r"rr#r#r$ test_tests  zTestSystemAPIs.test_testc Cstj}|j|ttjdd|j|dtjjdrft d}|j }WdQRXd|krft j dtjdd}|j|d|j||dS) NT)percpurOz /proc/cpuinfoz physical idz#cpuinfo doesn't include physical idF)logical) r/ cpu_countr6rVr?rDr-pathexistsopenreadr ZSkipTest)r"rfdZ cpuinfo_dataZphysicalr#r#r$test_cpu_counts      zTestSystemAPIs.test_cpu_countcCszxtd D]l}tjd|d}|jtj|js2tWdQRXtjd|d"}|jtjdd|jshtWdQRXqWdS) NrOrz$psutil._psplatform.cpu_count_logical) return_valuez%psutil._psplatform.cpu_count_physicalF)rr[)r[rN)rr5rCr/rrErF)r"valrIr#r#r$test_cpu_count_nones   z"TestSystemAPIs.test_cpu_count_nonecCs^d}tj}t|x,|D]$}|j|t|j|d||7}qW|j|t|t|dS)Nrg)r/r?sumrmrnrDr6str)r"rwtimescp_timer#r#r$test_cpu_timess    zTestSystemAPIs.test_cpu_timescCsDttj}tjdttj}||}|dks@|jd|dS)Ng?g?z difference %s)rr/r?r]rr})r"t1t2 differencer#r#r$test_cpu_times_time_increases:s    z,TestSystemAPIs.test_cpu_times_time_increasescCsxftjddD]V}d}t|x,|D]$}|j|t|j|d||7}q$W|j|t|t|qW|jttjdddttjdddS)NT)rrgF) r/r?rrmrnrDr6rrV)r"rrwrr#r#r$test_per_cpu_timesCs     z!TestSystemAPIs.test_per_cpu_timescCstjdd}tjd}xtj|krPqWtjdd}x.rO)delta)r/r?_makerrzassertAlmostEqualr{)r"baseZper_cpuZ summed_valuesZfieldr#r#r$test_cpu_times_comparisonts   z(TestSystemAPIs.test_cpu_times_comparisoncCsy<|j|t|j|d|j|d|j|dtjWn@tk r|}z$td|tj |tj |fWYdd}~XnXdS)NggY@z %s last=%s new=%sg) rmrnrDZ assertIsNotassertLessEqualr/rrFpprintZpformat)r"rvZlast_retZnew_reterrr#r#r$_test_cpu_percent~s   z TestSystemAPIs._test_cpu_percentc Csbtjdd}x.tdD]"}tjdd}|j||||}qW|jttjddWdQRXdS)NgMbP?)intervalrurOr[)r/ cpu_percentrrr9rB)r"lastr)newr#r#r$test_cpu_percents   zTestSystemAPIs.test_cpu_percentc Cstjddd}|jt|tjx>tdD]2}tjddd}x|D]}|j|||qDW|}q,W|jttjdddWdQRXdS)NgMbP?T)rrrurOr[) r/rr6rVrrrr9rB)r"rr)rrvr#r#r$test_per_cpu_percents  z#TestSystemAPIs.test_per_cpu_percentcCs`tjdd}xNtdD]B}tjdd}x|D]}|j|||q,W|jt||||}qWdS)NgMbP?)rru)r/cpu_times_percentrrr)r"rr)rrvr#r#r$test_cpu_times_percents   z%TestSystemAPIs.test_cpu_times_percentcCstjddd}|jt|tjx^tdD]R}tjddd}x:|D]2}x|D]}|j|||qNW|jt|||qDW|}q,WdS)NgMbP?T)rrru)r/rr6rVrrrr)r"rr)rcpurvr#r#r$test_per_cpu_times_percents  z)TestSystemAPIs.test_per_cpu_times_percentc CsrtjddddtjddD}tjd|d8x0tjddD] }x|D]}|j|ddqJWq@WWdQRXdS)NT)rcSs*g|]"}|jddtt|jDqS)cSsg|]}dqS)rr#)r(r)r#r#r$r*szQTestSystemAPIs.test_per_cpu_times_percent_negative...)rrrVrz)r(r)r#r#r$r*szFTestSystemAPIs.test_per_cpu_times_percent_negative..zpsutil.cpu_times)r)r/rr?rr5r)r"Z zero_timesrrvr#r#r$#test_per_cpu_times_percent_negatives  z2TestSystemAPIs.test_per_cpu_times_percent_negativec Cs2tjtj}|j|jd |jdks.t||jdks@t||j dksRt||j|jksft||j|j kszt|d|j kodknst|j t t drt jtj}d }|j|j|j|j |j |j |d |j |j|j|d tj}|jt}tj|WdQRX|j|jjtjdS)Nrwrxryrvrru disk_usagei)r)rwrxryrviiP)r/rr-getcwdr6rzrwrFrxryrvr`shutilrtempfileZmktempr9OSErrorZ exceptionerrnoENOENT)r"ZusageZ shutil_usageZ toleranceZfnameexcr#r#r$test_disk_usages($    zTestSystemAPIs.test_disk_usagec Cs(tr$|jttjtWdQRXdS)N)rr9UnicodeEncodeErrorr/rr)r"r#r#r$test_disk_usage_unicodes z&TestSystemAPIs.test_disk_usage_unicodecCstjddS)N.)r/r)r"r#r#r$test_disk_usage_bytessz$TestSystemAPIs.test_disk_usage_bytescCstjdd}|j||dx|D]}|j|jt|j|jt|j|jt|j|jtt rld|jkrlq t st j j |jst|n|jtstrt j j |jst|nt j j|jst||js t|q Wtjdd}|j||dxtjddD]}t syt j|jWnXtk rp}z:trJtrJ|jtjkrJw|jtjtjfkr`WYdd}~Xn@Xts~trt j j |jst|nt j j|jst||j|jt|j|jtqWdd}|t}dd tjddD}|j||tj|dS) NF)all)rZcdromTcSs2tjj|}xtjj|s(tjj|}qW|jS)N)r-rabspathismountdirnamelower)rr#r#r$find_mount_points z=TestSystemAPIs.test_disk_partitions..find_mount_pointcSsg|]}|jjqSr#) mountpointr)r(r)r#r#r$r*sz7TestSystemAPIs.test_disk_partitions..)r/Zdisk_partitionsrfrmZdevicerrZfstypeZoptsr r r-rrrFr risdirstatrrrZEIOZEPERMZEACCES__file__r,r)r"lsZdiskrrZmountZmountsr#r#r$test_disk_partitionssL     z#TestSystemAPIs.test_disk_partitionscslfdd}tjdd}||tjdd}j|gx.|D]&}j|j|t|||q>WdS)Ncs(j|d|jj|d|jj|d|jj|d|jj|d|jj|d|jj|d|jj|d|j|jdkst ||jdkst ||jdkst ||jdkst ||jdkst ||jdkst ||jdkst ||jdks$t |dS) NrrOrTrQr) r6Z bytes_sentZ bytes_recvZ packets_sentZ packets_recvZerrinZerroutZdropinZdropoutrF)nt)r"r#r$ check_ntuples z9TestSystemAPIs.test_net_io_counters..check_ntupleF)pernicT)r/net_io_countersassertNotEqualrfrmr)r"rretkeyr#)r"r$test_net_io_counterss       z#TestSystemAPIs.test_net_io_countersc CsNtjdid6}|jtjdd|jtjddi|js@tWdQRXdS)Nz"psutil._psplatform.net_io_counters)rF)rT)rr5rCr/rr6rErF)r"rIr#r#r$test_net_io_counters_no_nics8s  z+TestSystemAPIs.test_net_io_counters_no_nicsc Csttj}|st|tj}ttjtjtjg}x|j D]\}}|j |t |j t t|t |x|D]}|j |jt|j |jt |j |jt tdf|j |jt tdf|j|j|tjdkr|j |jtj||jr|jtjkr6tj|j}tj||j|jdfWdQRXnj|jtjkrtj|jdtjtjdtjd}|\} } } } } tj| | | }tj||j| WdQRXxB|j|j|j|j fD]*}|dk r|jtjkrt!||jqW|jr|j"|j qr|j rr|j"|jqrWq.check_ntupleF)perdiskzno disks on this system?TrOr[r[r[) r/disk_io_countersrFr6rVrerisdigitr4rA)r"rrrr#)r"r$test_disk_io_counterss      z$TestSystemAPIs.test_disk_io_countersc CsNtjdid6}|jtjdd|jtjddi|js@tWdQRXdS)Nz#psutil._psplatform.disk_io_counters)rF)rT)rr5rCr/rr6rErF)r"rIr#r#r$test_disk_io_counters_no_diskss  z-TestSystemAPIs.test_disk_io_counters_no_disksz unreliable on APPVEYOR or TRAVIScCstj}|j|gx|D]}|js,t||j|jt|j|jttdf|j dk rp|j|j ttdf|j|j |j dkst|t j j |j t str|j|jqtj|jqWdS)Ng)r/usersrrrFrmrZterminalrhostZstarteddatetimeZ fromtimestampr rrCr'r1)r"ruserr#r#r$ test_userss   zTestSystemAPIs.test_userscCsZtj}|j|jdx>|jD]4}t||}|j|dt r|dkr|j|dqWdS)N ctx_switches interruptssoft_interruptssyscallsr)rrrr)rr)r/Z cpu_statsr6rzr{rDrro)r"Zinfosrrr#r#r$test_cpu_statss   zTestSystemAPIs.test_cpu_statsz not suportedcs`fdd}tjdd}tr&| r&dS|s2t||tjddgtr\jt|tjdS)Ncshxb|D]Z}j|jdj|j|jx6|jD],}t||}j|ttt fj |dq0WqWdS)Ncurrentminrr)r r r) r6rzrr rr{rmr|r rnrD)rrrr)r"r#r$check_lss   z.TestSystemAPIs.test_cpu_freq..check_lsT)rF)r/Zcpu_freqrrFrr6rVr)r"r rr#)r"r$ test_cpu_freqs   zTestSystemAPIs.test_cpu_freqc Csddddddddd g }x"|D]}|jtt|t|d qWtjd krJtjsPttj s\t|j dd t j j krtj s~t|j dnd t j j krtjst|jtjtjtjgjdd|j d|j d|j d|j dn^dt j j ks dt j j kr"tjst|j d n&dt j j krntjs>t|j dn$tjsVttj sdt|j dx$|D]}|jtt|d|d qtWdS)Nr r rrrrrrr )rposixlinuxZbsdTrOsunossolarisdarwinF)rmr{r/rr-rr rFr removerplatformrrrr6rrrcountr rrH)r"namesrr#r#r$test_os_constantss>                      z TestSystemAPIs.test_os_constantsz not supportedcCstj}x|jD]x\}}|j|txb|D]Z}|j|jt|jdk rV|j|jd|jdk rn|j|jd|j dk r,|j|j dq,WqWdS)Nr) r/sensors_temperaturesrrmrlabelr rDhighcritical)r"tempsrentriesentryr#r#r$test_sensors_temperatures)s     z(TestSystemAPIs.test_sensors_temperaturesc Cspddgi}tjd|dN}tjdd dd }|js8t|j|jd |j|jd |j|j d WdQRXdS)NZcoretemprI@N@Q@z'psutil._psplatform.sensors_temperatures)rT)Z fahrenheitrg^@ga@gc@)rrr r!) rr5r/rrErFr6r rr)r"drIrr#r#r$#test_sensors_temperatures_fahreneit7s   z2TestSystemAPIs.test_sensors_temperatures_fahreneitz no batterycCsptj}|j|jd|j|jd|jtjtjfkrF|j|jdn|jtjkr^|j|j |j |j t dS)Nrru) r/Zsensors_batteryrDrvrZsecsleftZPOWER_TIME_UNKNOWNZPOWER_TIME_UNLIMITEDrfZ power_pluggedrmr)r"rr#r#r$test_sensors_batteryCs   z#TestSystemAPIs.test_sensors_batterycCsjtj}x\|jD]P\}}|j|tx:|D]2}|j|jt|j|jttf|j |jdq,WqWdS)Nr) r/Z sensors_fansrrmrrr r|r rD)r"Zfansrrrr#r#r$test_sensors_fansQs  z TestSystemAPIs.test_sensors_fans)C__name__ __module__ __qualname____doc__r%r&r<rKrkrlrpr ZskipIfr rtrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr-rrr r/rrrrrrrr rrrr#rrr$rr%r#r#r#r$r!;sh7     !       > <#  %  r!__main__)2r)rrrr-rrrcrrrr]r/rrrrrrrr r r Zpsutil._compatr Z psutil.testsr rrrrrrrrrrrrrrrrrrr ZTestCaser!r&rr#r#r#r$sh                               ' PK!,UU2__pycache__/test_memory_leaks.cpython-36.opt-1.pycnu[3 JZ=G@s<dZddlmZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl m Z ddl m Z ddl mZddl mZddl mZdd l mZdd lmZdd lmZdd lmZdd lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddlm$Z$ddlm%Z%ddlm&Z&ddlm'Z'ddlm(Z(dZ)d Z*d!Z+e'rd"nd#Z,e j-j.Z.e j/Z0e'rd"nd#Z,d$d%Z1d&d'Z2Gd(d)d)e(j3Z4Gd*d+d+e4Z5Gd,d-d-e5Z6Gd.d/d/e4Z7e8d0kr8e#e9dS)1a) Tests for detecting function memory leaks (typically the ones implemented in C). It does so by calling a function many times and checking whether process memory usage keeps increasing between calls or over time. Note that this may produce false positives (especially on Windows for some reason). )print_functionN)LINUX)OPENBSD)OSX)POSIX)SUNOS)WINDOWS)xrange)create_sockets)get_test_subprocess)HAS_CPU_AFFINITY) HAS_CPU_FREQ) HAS_ENVIRON) HAS_IONICE)HAS_MEMORY_MAPS)HAS_PROC_CPU_NUM)HAS_PROC_IO_COUNTERS) HAS_RLIMIT)HAS_SENSORS_BATTERY)HAS_SENSORS_FANS)HAS_SENSORS_TEMPERATURES) reap_children)run_test_module_by_name) safe_rmpath)skip_on_access_denied)TESTFN)TRAVIS)unittestiiTFcCstjto tdS)Nz worthless on LINUX (pure python))rskipIfrSKIP_PYTHON_IMPLr!r!)/usr/lib64/python3.6/test_memory_leaks.py skip_if_linuxFs r#cCstd }i}x(t|D]\}}d |d d >||<qWx8t|D],}|||kr>> bytes2human(10000) '9.8K' >>> bytes2human(100001221) '95.4M' KMGTPEZY z%.2f%sz%sB)r$r%r&r'r(r)r*r+) enumeratereversedfloat)nZsymbolsprefixisvaluer!r!r" bytes2humanKs r6c@sLeZdZdZeZeZeZ ddZ ddZ ddZ e dd Ze d d Zd S) TestMemLeakzBase framework class which calls a function many times and produces a failure if process memory usage keeps increasing between calls or over time. cCs tjdS)N)gccollect)selfr!r!r"setUpgszTestMemLeak.setUpcs~fdd}jddp$j}jddp6jjddpHj}x"tdD]}jfqTWjtjgjt j djt j g|j }|j } | |} | |krzd } tj|} x,tj| krjf| d7} qW~ tjj } | | }| | krzt| |}td |tjd d }|d 7}|t| t|| |f}j|dS)zTest a callable.cs2x"tD]}jfq W~tjdS)N)r _callr8r9)x)argsfunkwargsloopsr:r!r"call_many_timeslsz,TestMemLeak.execute..call_many_times tolerance_NZloops_Z retry_for_r-r,rzexta proc mem: %s)filez0+%s after %s calls, +%s after another %s calls, z+%s extra proc mem)pop tolerancerA retry_forranger<Z assertEqualr8Zgarbage threadingZ active_countthisprocchildren_get_memtimer9r6printsysstderrZfail)r:r?r>r@rBrFrGr=Zmem1Zmem2Zdiff1ZncallsZstop_atZmem3Zdiff2Zextra_proc_memmsgr!)r>r?r@rAr:r"executejsB     zTestMemLeak.executecs"fdd}j|dS)zRConvenience function which tests a callable raising an exception. csjfdS)N)Z assertRaisesr!)r>excr?r@r:r!r"callsz'TestMemLeak.execute_w_exc..callN)rR)r:rSr?r>r@rTr!)r>rSr?r@r:r" execute_w_excszTestMemLeak.execute_w_exccCs$ts ts trtjjStjjSdS)N)rrrrJmemory_full_infoZuss memory_infoZrssr!r!r!r"rLs  zTestMemLeak._get_memcOs|||dS)Nr!)r?r>r@r!r!r"r<szTestMemLeak._callN)__name__ __module__ __qualname____doc__MEMORY_TOLERANCErFLOOPSrA RETRY_FORrGr;rRrU staticmethodrLr<r!r!r!r"r7^s; r7c@seZdZdZeZddZeddZeddZ edd Z ed d Z e j e d ed dZe j e d eddZeddZddZddZe j e dddZe j e dddZe j e deddZe j eddd Zed!d"Zeeed#d$d%Ze j e d&d'd(Ze j e d ed)d*Z ed+d,Z!eeed#d-d.Z"ed/d0Z#ee j e$ dd1d2Z%ed3d4Z&ed5d6Z'e j e d ed7d8Z(e j eoe)d9d:d;Z*edd?Z-e j e, dd@dAZ.edBdCZ/e j e0dDe j e1 dedEdFZ2e j e3 dGe j e4 ddHdIZ5e j e3 dGe j e4 ddJdKZ6ee j edLdMdNZ7e j e8 ddOdPZ9e j e d&dQdRZ:dSS)TTestProcessObjectLeaksz$Test leaks of Process class methods.cCsNtd}x@ttjD]2}|jdr$q||kr.q|jt|d||dqWdS)Npidas_dictrK cpu_affinity cpu_percentionice is_runningkillmemory_info_exmemory_percentniceoneshotparentrlimit send_signalsuspend terminatewait_test_)rQ)rarbrKrcrdrerfrgrhrirjrkrlrmrnrorprq)setdirpsutilProcess startswith assertTruehasattr)r:skipnamer!r!r" test_coverages z$TestProcessObjectLeaks.test_coveragecCs|j|jjdS)N)rRprocr|)r:r!r!r" test_namesz TestProcessObjectLeaks.test_namecCs|j|jjdS)N)rRr~Zcmdline)r:r!r!r" test_cmdlinesz#TestProcessObjectLeaks.test_cmdlinecCs|j|jjdS)N)rRr~Zexe)r:r!r!r"test_exeszTestProcessObjectLeaks.test_execCs|j|jjdS)N)rRr~Zppid)r:r!r!r" test_ppidsz TestProcessObjectLeaks.test_ppidz POSIX onlycCs|j|jjdS)N)rRr~Zuids)r:r!r!r" test_uidssz TestProcessObjectLeaks.test_uidscCs|j|jjdS)N)rRr~Zgids)r:r!r!r" test_gidssz TestProcessObjectLeaks.test_gidscCs|j|jjdS)N)rRr~Zstatus)r:r!r!r" test_statussz"TestProcessObjectLeaks.test_statuscCs|j|jjdS)N)rRr~rj)r:r!r!r" test_nice_getsz$TestProcessObjectLeaks.test_nice_getcCstj}|j|jj|dS)N)rJrjrRr~)r:Znicenessr!r!r" test_nice_setsz$TestProcessObjectLeaks.test_nice_setz not supportedcCs|j|jjdS)N)rRr~re)r:r!r!r"test_ionice_getsz&TestProcessObjectLeaks.test_ionice_getcCsVtrtj}|j|jj|n4|j|jjtjtjt j t j dd}|j t|dS)Nr,r)rrJrerRr~rvZIOPRIO_CLASS_NONE functoolspartialcextZproc_ioprio_setosgetpidrUOSError)r:r5r?r!r!r"test_ionice_sets z&TestProcessObjectLeaks.test_ionice_setcCs|j|jjdS)N)rRr~Z io_counters)r:r!r!r"test_io_counterssz'TestProcessObjectLeaks.test_io_counterszworthless on POSIXcCs|j|jjdS)N)rRr~Zusername)r:r!r!r" test_username sz$TestProcessObjectLeaks.test_usernamecCs|j|jjdS)N)rRr~Z create_time)r:r!r!r"test_create_timesz'TestProcessObjectLeaks.test_create_time)Zonly_ifcCs|j|jjdS)N)rRr~Z num_threads)r:r!r!r"test_num_threadssz'TestProcessObjectLeaks.test_num_threadsz WINDOWS onlycCs|j|jjdS)N)rRr~Z num_handles)r:r!r!r"test_num_handlessz'TestProcessObjectLeaks.test_num_handlescCs|j|jjdS)N)rRr~Znum_fds)r:r!r!r" test_num_fdssz#TestProcessObjectLeaks.test_num_fdscCs|j|jjdS)N)rRr~Znum_ctx_switches)r:r!r!r"test_num_ctx_switches!sz,TestProcessObjectLeaks.test_num_ctx_switchescCs|j|jjdS)N)rRr~Zthreads)r:r!r!r" test_threads%sz#TestProcessObjectLeaks.test_threadscCs|j|jjdS)N)rRr~ cpu_times)r:r!r!r"test_cpu_times*sz%TestProcessObjectLeaks.test_cpu_timescCs|j|jjdS)N)rRr~Zcpu_num)r:r!r!r" test_cpu_num.sz#TestProcessObjectLeaks.test_cpu_numcCs|j|jjdS)N)rRr~rW)r:r!r!r"test_memory_info3sz'TestProcessObjectLeaks.test_memory_infocCs|j|jjdS)N)rRr~rV)r:r!r!r"test_memory_full_info7sz,TestProcessObjectLeaks.test_memory_full_infocCs|j|jjdS)N)rRr~Zterminal)r:r!r!r" test_terminal;sz$TestProcessObjectLeaks.test_terminalz worthless on POSIX (pure python)cCs|j|jjdS)N)rRr~resume)r:r!r!r" test_resume@sz"TestProcessObjectLeaks.test_resumecCs|j|jjdS)N)rRr~cwd)r:r!r!r"test_cwdEszTestProcessObjectLeaks.test_cwdcCs|j|jjdS)N)rRr~rc)r:r!r!r"test_cpu_affinity_getIsz,TestProcessObjectLeaks.test_cpu_affinity_getcCs4tj}|j|jj|ts0|jt|jjdgdS)Nr,r)rJrcrRr~rrU ValueError)r:Zaffinityr!r!r"test_cpu_affinity_setMsz,TestProcessObjectLeaks.test_cpu_affinity_setc Cs0ttttd|j|jjWdQRXdS)Nw)rropenrRr~Z open_files)r:r!r!r"test_open_filesTs z&TestProcessObjectLeaks.test_open_filesztoo slow on OSXcCs|j|jjdS)N)rRr~Z memory_maps)r:r!r!r"test_memory_maps[sz'TestProcessObjectLeaks.test_memory_mapsz LINUX onlycCs|j|jjtjdS)N)rRr~rmrv RLIMIT_NOFILE)r:r!r!r"test_rlimit_getasz&TestProcessObjectLeaks.test_rlimit_getcCs6tjtj}|j|jjtj||jt|jjddS)Nr,r)rJrmrvrrRr~rUr)r:limitr!r!r"test_rlimit_setfs z&TestProcessObjectLeaks.test_rlimit_setzworthless on WINDOWSc Cs2t"trdnd}|j|jj|WdQRXdS)NZinetall)r rrRr~Z connections)r:Zkindr!r!r"test_connectionsms z'TestProcessObjectLeaks.test_connectionscCs|j|jjdS)N)rRr~environ)r:r!r!r" test_environysz#TestProcessObjectLeaks.test_environcCs|jtjtjdS)N)rRr proc_inforr)r:r!r!r"test_proc_info}sz%TestProcessObjectLeaks.test_proc_infoN);rXrYrZr[rJr~r}r#rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr rrr rrrrrrrrrrrrrrr!r!r!r"r`sh            r`cspeZdZdZefddZefddZddZerhdd Z d d Z d d Z ddZ ddZ ddZZS)TestTerminatedProcessLeakszRepeat the tests above looking for leaks occurring when dealing with terminated processes raising NoSuchProcess exception. The C functions are still invoked but will follow different code paths. We'll check those code paths. cs:tt|jt}tj|j|_|jj|jj dS)N) superr setUpClassr rvrwrar~rgrq)clsp) __class__r!r"rs  z%TestTerminatedProcessLeaks.setUpClasscstt|jtdS)N)rr tearDownClassr)r)rr!r"rsz(TestTerminatedProcessLeaks.tearDownClassc Os*y|||Wntjk r$YnXdS)N)rvZ NoSuchProcess)r:r?r>r@r!r!r"r<sz TestTerminatedProcessLeaks._callcCs|j|jjdS)N)rRr~rg)r:r!r!r" test_killsz$TestTerminatedProcessLeaks.test_killcCs|j|jjdS)N)rRr~rp)r:r!r!r"test_terminatesz)TestTerminatedProcessLeaks.test_terminatecCs|j|jjdS)N)rRr~ro)r:r!r!r" test_suspendsz'TestTerminatedProcessLeaks.test_suspendcCs|j|jjdS)N)rRr~r)r:r!r!r"rsz&TestTerminatedProcessLeaks.test_resumecCs|j|jjdS)N)rRr~rq)r:r!r!r" test_waitsz$TestTerminatedProcessLeaks.test_waitcsfdd}j|dS)NcsDytjjjStk r>}z|jtjkr.WYdd}~XnXdS)N)rrr~rarerrnoZESRCH)err)r:r!r"rTs  z7TestTerminatedProcessLeaks.test_proc_info..call)rR)r:rTr!)r:r"rs z)TestTerminatedProcessLeaks.test_proc_info)rXrYrZr[ classmethodrrr<rrrrrrr __classcell__r!r!)rr"rsrc@seZdZdZddZeddZeddZedd Zed d Z d d Z ee j e dddZddZe j edddZe j eoedddZe j eoedddZddZe j eoejjd dedd Zed!d"Zed#d$Ze j ed%e j eo&ejd&kd'd(d)Z d*d+Z!e j e"d,d-d.Z#ee j e$ dd/d0Z%ee j e& dd1d2Z'ee j e( dd3d4Z)ed5d6Z*e j e+d7d8d9Z,e+rd:d;Z-dd?Z/d@dAZ0dBdCZ1dDS)ETestModuleFunctionsLeaksz&Test leaks of psutil module functions.cCsHtd }x:tjD]0}|jsq||kr(q|jt|d||d qWdS) N version_info __version__ process_iter wait_procsrdcpu_times_percent cpu_countrs)rQ)rrrrrdrr)rtrv__all__islowerryrz)r:r{r|r!r!r"r}s z&TestModuleFunctionsLeaks.test_coveragecCs|jtjdddS)NT)logical)rRrvr)r:r!r!r"test_cpu_count_logicalsz/TestModuleFunctionsLeaks.test_cpu_count_logicalcCs|jtjdddS)NF)r)rRrvr)r:r!r!r"test_cpu_count_physicalsz0TestModuleFunctionsLeaks.test_cpu_count_physicalcCs|jtjdS)N)rRrvr)r:r!r!r"rsz'TestModuleFunctionsLeaks.test_cpu_timescCs|jtjdddS)NT)Zpercpu)rRrvr)r:r!r!r"test_per_cpu_timessz+TestModuleFunctionsLeaks.test_per_cpu_timescCs|jtjdS)N)rRrvZ cpu_stats)r:r!r!r"test_cpu_statssz'TestModuleFunctionsLeaks.test_cpu_statsz not supportedcCs|jtjdS)N)rRrvZcpu_freq)r:r!r!r" test_cpu_freqsz&TestModuleFunctionsLeaks.test_cpu_freqcCs|jtjdS)N)rRrvZvirtual_memory)r:r!r!r"test_virtual_memorysz,TestModuleFunctionsLeaks.test_virtual_memoryz&worthless on SUNOS (uses a subprocess)cCs|jtjdS)N)rRrvZ swap_memory)r:r!r!r"test_swap_memorysz)TestModuleFunctionsLeaks.test_swap_memoryz worthless on POSIX (pure python)cCs|jtjtjdS)N)rRrvZ pid_existsrr)r:r!r!r"test_pid_existssz(TestModuleFunctionsLeaks.test_pid_existscCs|jtjddS)N.)rRrvZ disk_usage)r:r!r!r"test_disk_usagesz(TestModuleFunctionsLeaks.test_disk_usagecCs|jtjdS)N)rRrvZdisk_partitions)r:r!r!r"test_disk_partitionssz-TestModuleFunctionsLeaks.test_disk_partitionsz/proc/diskstatsz3/proc/diskstats not available on this Linux versioncCs|jtjdddS)NF)nowrap)rRrvZdisk_io_counters)r:r!r!r"test_disk_io_counterssz.TestModuleFunctionsLeaks.test_disk_io_counterscCs|jtjdS)N)rRrvZpids)r:r!r!r" test_pidssz"TestModuleFunctionsLeaks.test_pidscCs|jtjdddS)NF)r)rRrvZnet_io_counters)r:r!r!r"test_net_io_counterssz-TestModuleFunctionsLeaks.test_net_io_countersz worthless on Linux (pure python)rzneed root accessc Cs"t|jtjWdQRXdS)N)r rRrvZnet_connections)r:r!r!r"test_net_connectionssz-TestModuleFunctionsLeaks.test_net_connectionscCs|jtjtrdndddS)NPi)rCi@)rRrvZ net_if_addrsr)r:r!r!r"test_net_if_addrssz*TestModuleFunctionsLeaks.test_net_if_addrszEPERM on traviscCs|jtjdS)N)rRrvZ net_if_stats)r:r!r!r"test_net_if_statssz*TestModuleFunctionsLeaks.test_net_if_statscCs|jtjdS)N)rRrvZsensors_battery)r:r!r!r"test_sensors_battery$sz-TestModuleFunctionsLeaks.test_sensors_batterycCs|jtjdS)N)rRrvZsensors_temperatures)r:r!r!r"test_sensors_temperatures)sz2TestModuleFunctionsLeaks.test_sensors_temperaturescCs|jtjdS)N)rRrvZ sensors_fans)r:r!r!r"test_sensors_fans.sz*TestModuleFunctionsLeaks.test_sensors_fanscCs|jtjdS)N)rRrvZ boot_time)r:r!r!r"test_boot_time5sz'TestModuleFunctionsLeaks.test_boot_timez(XXX produces a false positive on WindowscCs|jtjdS)N)rRrvZusers)r:r!r!r" test_users:sz#TestModuleFunctionsLeaks.test_userscCs|jtjdS)N)rRrZwinservice_enumerate)r:r!r!r"test_win_service_iterBsz.TestModuleFunctionsLeaks.test_win_service_itercCsdS)Nr!)r:r!r!r"test_win_service_getEsz-TestModuleFunctionsLeaks.test_win_service_getcCs"ttjj}|jtj|dS)N)nextrvwin_service_iterr|rRrZwinservice_query_config)r:r|r!r!r"test_win_service_get_configHsz4TestModuleFunctionsLeaks.test_win_service_get_configcCs"ttjj}|jtj|dS)N)rrvrr|rRrZwinservice_query_status)r:r|r!r!r"test_win_service_get_statusLsz4TestModuleFunctionsLeaks.test_win_service_get_statuscCs"ttjj}|jtj|dS)N)rrvrr|rRrZwinservice_query_descr)r:r|r!r!r" test_win_service_get_descriptionPsz9TestModuleFunctionsLeaks.test_win_service_get_descriptionN)2rXrYrZr[r}r#rrrrrrrr rrrrrr rrrrrpathexistsrrrrgetuidrrrrrrrrrrrrrrrrrrr!r!r!r"rsR   $r__main__):r[Z __future__rrrr8rrOrIrMrvZpsutil._commonrrrrrrZpsutil._compatr Z psutil.testsr r r r rrrrrrrrrrrrrrrrr]r\r^r Z _psplatformrrwrJr#r6ZTestCaser7r`rrrX__file__r!r!r!r" sl                            cB< PK!)33%__pycache__/test_posix.cpython-36.pycnu[3 JZ?@sdZddlZddlZddlZddlZddlZddlZddlZddlZddlm Z ddlm Z ddlm Z ddlm Z ddlm Z ddlmZdd lmZdd lmZdd lmZdd lmZdd lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddZ"ddZ#ddZ$ej%e d Gd!d"d"ej&Z'ej%e d Gd#d$d$ej&Z(e)d%kree*dS)&zPOSIX specific tests.N)AIX)BSD)LINUX)OPENBSD)OSX)POSIX)SUNOS)callable)PY3)APPVEYOR)get_kernel_version)get_test_subprocess)mock) PYTHON_EXE) reap_children)retry_before_failing)run_test_module_by_name)sh)skip_on_access_denied)TRAVIS)unittest) wait_for_pid)whichc Cspts|jdd}tr |jdd}tr0|jdd}t|}tsN|jddj}yt|Stk rj|SXd S) zkExpects a ps command with a -o argument and parse the result returning only the value of interest. z --no-headers  z-o startz-o stimez-o rssz -o rssize N) rreplacerrrsplitstripint ValueError)cmdoutputr#"/usr/lib64/python3.6/test_posix.pyps+s   r%cCs&d}tr d}td||fjddS)NcommandZcommzps --no-headers -o %s -p %srr)rr%r)pidfieldr#r#r$ps_nameIsr)cCs d}ts trd}td||fS)Nr&argszps --no-headers -o %s -p %s)rrr%)r'r(r#r#r$ps_argsPsr+z POSIX onlyc@seZdZdZeddZeddZddZdd Zd d Z d d Z ddZ e e ddZe e ddZddZddZddZddZejepedddZdd Zd!d"Zejed#ejed$d%d&Zd'd(Zd)S)* TestProcesszBCompare psutil results against 'ps' command line utility (mainly).cCs&ttddgtjdj|_t|jdS)Nz-Ez-O)stdin)r r subprocessPIPEr'r)clsr#r#r$ setUpClass[s zTestProcess.setUpClasscCs tdS)N)r)r0r#r#r$ tearDownClassaszTestProcess.tearDownClasscCs.td|j}tj|jj}|j||dS)Nzps --no-headers -o ppid -p %s)r%r'psutilProcessZppid assertEqual)selfZppid_psZ ppid_psutilr#r#r$ test_ppideszTestProcess.test_ppidcCs0td|j}tj|jjj}|j||dS)Nzps --no-headers -o uid -p %s)r%r'r3r4uidsrealr5)r6Zuid_psZ uid_psutilr#r#r$test_uidjszTestProcess.test_uidcCs0td|j}tj|jjj}|j||dS)Nzps --no-headers -o rgid -p %s)r%r'r3r4Zgidsr9r5)r6Zgid_psZ gid_psutilr#r#r$test_gidoszTestProcess.test_gidcCs.td|j}tj|jj}|j||dS)Nzps --no-headers -o user -p %s)r%r'r3r4usernamer5)r6Z username_psZusername_psutilr#r#r$ test_usernametszTestProcess.test_usernamec CsJtj}tjdtd*}|j|jt|jj |j s)rr?r3 AccessDeniedr4r5rP)r6rPrDr#r#r$test_name_long_cmdline_ad_excs z)TestProcess.test_name_long_cmdline_ad_exccCs\d}tjd|d@tjdtjdddtj}|jtj|jWdQRXWdQRXdS)Nzlong-program-namezpsutil._psplatform.Process.name)rTz"psutil._psplatform.Process.cmdlinerrK)r>)rr?r3Z NoSuchProcessr4 assertRaisesrP)r6rPrDr#r#r$test_name_long_cmdline_nsp_excs z*TestProcess.test_name_long_cmdline_nsp_exczps -o start not availablecCshtd|jjdd}tj|jj}tjj|jd}t |}tjj|jd}|j |||gdS)Nzps --no-headers -o start -p %srrz%H:%M:%S) r%r'rr3r4Z create_timedatetimeZ fromtimestampZstrftimeroundassertIn)r6Ztime_psZ time_psutilZtime_psutil_tstampZround_time_psutilZround_time_psutil_tstampr#r#r$test_create_times  zTestProcess.test_create_timec Cs`t|j}tj|jj}y|j||Wn0tk rZ|dt|}|j||YnXdS)N)r)r'r3r4Zexer5rClen)r6Z ps_pathnameZpsutil_pathnameZadjusted_ps_pathnamer#r#r$test_exes zTestProcess.test_execCs0t|j}djtj|jj}|j||dS)Nr)r+r'joinr3r4rUr5)r6Z ps_cmdlineZpsutil_cmdliner#r#r$ test_cmdlines zTestProcess.test_cmdlineznot reliable on SUNOSznot reliable on AIXcCs*td|j}tjj}|j||dS)Nzps --no-headers -o nice -p %s)r%r'r3r4nicer5)r6Zps_niceZ psutil_nicer#r#r$ test_nices zTestProcess.test_nicec sfdd}tjtj}g}ddddddd d d d g }trNtdkrN|jdtrftdkrf|jdxttjD]jdsr|krqrqry0|j }xt d D]}||qW|j }Wntj k rYqrXt ||dkrrd||f}|j|qrW|r|j ddj|dS)NcsBf}t|d}|dk r:t|r:dkr0tjf}||n|dS)Nrlimit)getattrr r3Z RLIMIT_NOFILE)rDattrr*)rPr#r$calls  z&TestProcess.test_num_fds..callZ terminatekillZsuspendZresumercZ send_signalwaitZchildrenZas_dictZmemory_info_ex$reZnum_ctx_switches_rz@failure while processing Process.%s method (before=%s, after=%s)r)rkrlrm)rkrlrn)r3r4rLgetpidrr appenddir startswithZnum_fdsrangerWabsfailra) r6rhrDZfailuresZ ignored_namesZnum1xZnum2rvr#)rPr$ test_num_fdss4      zTestProcess.test_num_fdsN)__name__ __module__ __qualname____doc__ classmethodr1r2r7r:r;r=rErrrIrJrSrVrXrZrskipIfrrr^r`rbrrrdrxr#r#r#r$r,Ws,           r,c@seZdZdZeddZejedeje deje d ddd Z eje p`e o`e j d ed d Zd dZddZddZddZejedddZdS)TestSystemAPIszTest some system APIs.cCststrddddg}n ddddg}t|tjd}|jdj}|jdksPtt rbt |t j j }g}x<|jdd dD]&}|rzt|jdj}|j|qzW|j|jtj}|j|jtstrd|kr|jdd|j||dS) Nr%z-Az-or'Zax)stdoutrrr)rrr r.r/Z communicaterZpollrCr rAsysrencodingrrrqremover'r3Zpidssortrrinsertr5)r6r!rDr"Zpids_psliner'Z pids_psutilr#r#r$ test_pids s(   zTestSystemAPIs.test_pidszunreliable on SUNOSzunreliable on TRAVISZifconfigzno ifconfig cmdcCsVtd}xHtjddjD]4}x.|jD]}|j|r(Pq(W|jd||fqWdS)Nz ifconfig -aT)Zpernicz/couldn't find %s nic in 'ifconfig -a' output %s)rr3Znet_io_counterskeysrrsrv)r6r"Znicrr#r#r$test_nic_names?s zTestSystemAPIs.test_nic_namesz unreliable on APPVEYOR or TRAVIScCsxtd}|jd}dd|D}dd|D}|jt|ttjx,tjD] }|j|j||j|j|qPWdS)NZwhorcSsg|]}|jdqS)r)r).0rwr#r#r$ Tsz-TestSystemAPIs.test_users..cSsg|]}|jdqS)r)r)rrwr#r#r$rUs) rrr5r_r3usersr]rPZterminal)r6outlinesrZ terminalsur#r#r$ test_usersNs zTestSystemAPIs.test_usersc CsFtjdttjdd&}|jttjjt j |j s8t WdQRXdS)Nzpsutil._psposix.os.killrK)r>) rr?OSErrorerrnoEBADFrYr3_psposixZ pid_existsrLrprBrC)r6mr#r#r$test_pid_exists_let_raise[sz(TestSystemAPIs.test_pid_exists_let_raisec CsFtjdttjdd&}|jttjjt j |j s8t WdQRXdS)Nzpsutil._psposix.os.waitpidrK)r>) rr?rrrrYr3rwait_pidrLrprBrC)r6rr#r#r$test_os_waitpid_let_raisedsz(TestSystemAPIs.test_os_waitpid_let_raisec CsNtjdttjdd.}|jtjjtjj t j dd|j s@t WdQRXdS)Nzpsutil._psposix.os.waitpidrK)r>g{Gz?)Ztimeout)rr?rrZEINTRrYr3rZTimeoutExpiredrrLrprBrC)r6rr#r#r$test_os_waitpid_eintrls z$TestSystemAPIs.test_os_waitpid_eintrc Cs>tjddd&}|jttjjtj|j s0t WdQRXdS)Nzpsutil._psposix.os.waitpidr)rT)rr) rr?rYr r3rrrLrprBrC)r6rr#r#r$test_os_waitpid_bad_ret_statusus  z-TestSystemAPIs.test_os_waitpid_bad_ret_statuszunreliable on AIXc Csdd}d }xtjddD]}tj|j}y||j\}}}}WnLtk r} z0t| j} d| ksvd| ksvd | krzwnWYdd} ~ XqX|j|j ||d |j|j ||d |j|j ||d |j|j |d d qWdS)NcSsvtd|j}|jdd}|j}t|dd}t|dd}t|dd}t|djdd }||||fS) Nzdf -k %srrirk%rK)rrrrfloatr)devicerrZfieldstotalusedfreepercentr#r#r$dfsz*TestSystemAPIs.test_disk_usage..dfriF)allzno such file or directoryzraw devices not supportedzpermission denied)Zdeltarii@) r3Zdisk_partitionsZ disk_usageZ mountpointr RuntimeErrorrArOZassertAlmostEqualrrrr) r6rZ tolerancepartZusagerrrrerrr#r#r$test_disk_usage~s"   zTestSystemAPIs.test_disk_usageN)ryrzr{r|rrrr~rrrrr r3rrrrrrrrr#r#r#r$rs       r__main__)+r|r[rrLrQr.rrFr3rrrrrrrZpsutil._compatr r Z psutil.testsr r r rrrrrrrrrrrr%r)r+r~ZTestCaser,rry__file__r#r#r#r$sT                        E  PK!P([[)__pycache__/test_contracts.cpython-36.pycnu[3 JZ2^@sdZddlZddlZddlZddlZddlZddlZddlmZddl m Z ddl m Z ddl m Z ddl m Z ddl mZdd l mZdd l mZdd l mZdd l mZdd l mZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddlm$Z$ddlm%Z%ddlm&Z&ddlm'Z'ddl Z Gd d!d!e$j(Z)Gd"d#d#e$j(Z*Gd$d%d%e$j(Z+Gd&d'd'e$j(Z,e-d(kre e.dS))zContracts tests. These tests mainly check API sanity in terms of returned types and APIs availability. Some of these are duplicates of tests test_system.py and test_process.py N)closing)AIX)BSD)FREEBSD)LINUX)NETBSD)OPENBSD)OSX)POSIX)SUNOS)WINDOWS)callable)long)bind_unix_socket)check_connection_ntuple)get_kernel_version)HAS_CONNECTIONS_UNIX) HAS_RLIMIT)HAS_SENSORS_FANS)HAS_SENSORS_TEMPERATURES) is_namedtuple)run_test_module_by_name) safe_rmpath)skip_on_access_denied)TESTFN)unittest)unix_socket_path)VALID_PROC_STATUSES)warnc@seZdZdZddZddZddZdd Zd d Zd d Z ddZ ddZ ddZ ddZ ddZddZddZddZddZd d!Zd"d#Zd$d%Zd&d'Zd(d)Zd*d+Zd,d-Zd.S)/TestAvailabilityzQMake sure code reflects what doc promises in terms of APIs availability. cCs$tp tp t}|jttjd|dS)N cpu_affinity)rr r assertEqualhasattrpsutilProcess)selfhasitr'&/usr/lib64/python3.6/test_contracts.pytest_cpu_affinity<s z"TestAvailability.test_cpu_affinitycCs(|jttdt|jttdtdS)NZwin_service_iterZwin_service_get)r!r"r#r )r%r'r'r(test_win_service@sz!TestAvailability.test_win_servicecCs|jttdtptptdS)NZ PROCFS_PATH)r!r"r#rr r)r%r'r'r(test_PROCFS_PATHDs z!TestAvailability.test_PROCFS_PATHcCsj|j}|ttdt|ttdt|ttdt|ttdt|ttdt|ttdtdS)NZABOVE_NORMAL_PRIORITY_CLASSZBELOW_NORMAL_PRIORITY_CLASSZHIGH_PRIORITY_CLASSZIDLE_PRIORITY_CLASSZNORMAL_PRIORITY_CLASSZREALTIME_PRIORITY_CLASS)r!r"r#r )r%aer'r'r(test_win_priorityHsz"TestAvailability.test_win_prioritycCsJ|j}|ttdt|ttdt|ttdt|ttdtdS)NZIOPRIO_CLASS_NONEZIOPRIO_CLASS_RTZIOPRIO_CLASS_BEZIOPRIO_CLASS_IDLE)r!r"r#r)r%r,r'r'r(test_linux_ioprioQs z"TestAvailability.test_linux_iopriocCsH|j}totdk}|ttjd||ttd||ttd||ttd||ttd||ttd ||ttd ||ttd ||ttd ||ttd ||ttd||ttd||ttd|totdk}|ttd||ttd||ttd||ttd||ttd|dS)N$rlimitZ RLIM_INFINITYZ RLIMIT_ASZ RLIMIT_COREZ RLIMIT_CPUZ RLIMIT_DATAZ RLIMIT_FSIZEZ RLIMIT_LOCKSZRLIMIT_MEMLOCK RLIMIT_NOFILEZ RLIMIT_NPROCZ RLIMIT_RSSZ RLIMIT_STACKrZRLIMIT_MSGQUEUEZ RLIMIT_NICEZ RLIMIT_RTPRIOZ RLIMIT_RTTIMEZRLIMIT_SIGPENDING)r/r0r1)r4r)r!rrr"r#r$)r%r,r&r'r'r(test_linux_rlimitXs*z"TestAvailability.test_linux_rlimitcCs:totjjdptjjd}|jttd|p2tp2tdS)Nz/sys/devices/system/cpu/cpufreqz$/sys/devices/system/cpu/cpu0/cpufreqZcpu_freq) rospathexistsr!r"r#r r )r%linuxr'r'r( test_cpu_freqps  zTestAvailability.test_cpu_freqcCs|jttdtdS)Nsensors_temperatures)r!r"r#r)r%r'r'r(test_sensors_temperaturesvsz*TestAvailability.test_sensors_temperaturescCs|jttdtdS)N sensors_fans)r!r"r#r)r%r'r'r(test_sensors_fansysz"TestAvailability.test_sensors_fanscCs"|jttdtptptptdS)NZsensors_battery)r!r"r#rr rr )r%r'r'r( test_battery|s zTestAvailability.test_batterycCs |jttjdtptptdS)Nenviron)r!r"r#r$rr r )r%r'r'r(test_proc_environsz"TestAvailability.test_proc_environcCs|jttjdtdS)Nuids)r!r"r#r$r )r%r'r'r(test_proc_uidsszTestAvailability.test_proc_uidscCs|jttjdtdS)NrB)r!r"r#r$r )r%r'r'r(test_proc_gidsszTestAvailability.test_proc_gidscCs|jttjdtdS)Nterminal)r!r"r#r$r )r%r'r'r(test_proc_terminalsz#TestAvailability.test_proc_terminalcCs|jttjdtptdS)Nionice)r!r"r#r$rr )r%r'r'r(test_proc_ionicesz!TestAvailability.test_proc_ionicecCs|jttjdtdS)Nr2)r!r"r#r$r)r%r'r'r(test_proc_rlimitsz!TestAvailability.test_proc_rlimitcCs(ttjd}|j|tstrdnddS)N io_countersFT)r"r#r$r!r r )r%r&r'r'r(test_proc_io_counterss z&TestAvailability.test_proc_io_counterscCs|jttjdtdS)Nnum_fds)r!r"r#r$r )r%r'r'r(test_proc_num_fdssz"TestAvailability.test_proc_num_fdscCs|jttjdtdS)N num_handles)r!r"r#r$r )r%r'r'r(test_proc_num_handlessz&TestAvailability.test_proc_num_handlescCs |jttjdtptptdS)Nr )r!r"r#r$rr r)r%r'r'r(test_proc_cpu_affinitysz'TestAvailability.test_proc_cpu_affinitycCs |jttjdtptptdS)Ncpu_num)r!r"r#r$rrr )r%r'r'r(test_proc_cpu_numsz"TestAvailability.test_proc_cpu_numcCs,ttjd}|j|tststr"dnddS)N memory_mapsFT)r"r#r$r!rrr)r%r&r'r'r(test_proc_memory_mapss z&TestAvailability.test_proc_memory_mapsN)__name__ __module__ __qualname____doc__r)r*r+r-r.r5r:r<r>r?rArCrDrFrHrIrKrMrOrPrRrTr'r'r'r(r7s. rc@seZdZddZdS)TestDeprecationsc Csdtjdd}tjjWdQRX|d}|j|jt|jdt |j |jdt |j dS)NT)recordrzmemory_info_ex() is deprecatedzuse memory_info() instead) warningscatch_warningsr#r$memory_info_exassertIsInstancecategory FutureWarningassertInstrmessage)r%Zwswr'r'r(test_memory_info_exs z$TestDeprecations.test_memory_info_exN)rUrVrWrer'r'r'r(rYsrYc@seZdZdZeddZddZddZdd Zd d Z e j e d e j e d eedddZddZddZddZe j e dddZe j e dddZddZdS) TestSystemzCheck the return types of system related APIs. Mainly we want to test we never return unicode on Python 2, see: https://github.com/giampaolo/psutil/issues/1039 cCstj|_dS)N)r#r$proc)clsr'r'r( setUpClassszTestSystem.setUpClasscCs ttdS)N)rr)r%r'r'r(tearDownszTestSystem.tearDowncCs>tj}t|stx$|D]}|j|t|j|dqWdS)Nr)r# cpu_timesrAssertionErrorr^floatassertGreaterEqual)r%retnr'r'r(test_cpu_timess    zTestSystem.test_cpu_timescCs&x tjddD]}|j|tqWdS)NT)Zperdisk)r#Zdisk_io_countersr^rb)r%kr'r'r(test_io_countersszTestSystem.test_io_counterscCsNxHtjD]<}|j|jt|j|jt|j|jt|j|jtq WdS)N)r#Zdisk_partitionsr^ZdevicerbZ mountpointZfstypeZopts)r%Zdiskr'r'r(test_disk_partitionss zTestSystem.test_disk_partitionsz POSIX onlyzcan't list UNIX sockets)Zonly_ifcCs^tN}tt|6tjdd}|s*tx|D]}|j|jtq0WWdQRXWdQRXdS)NZunix)Zkind) rrrr#Znet_connectionsrlr^Zladdrrb)r%nameZconsconnr'r'r(test_net_connectionss   zTestSystem.test_net_connectionscCsrxltjjD]\\}}|j|txF|D]>}|j|jt|j|jttdf|j|jttdfq(WqWdS)N) r#Z net_if_addrsitemsr^rbZaddressZnetmasktypeZ broadcast)r%ifnameZaddrsaddrr'r'r(test_net_if_addrss   zTestSystem.test_net_if_addrscCs*x$tjjD]\}}|j|tqWdS)N)r#Z net_if_statsrxr^rb)r%rz_r'r'r(test_net_if_statsszTestSystem.test_net_if_statscCs.x(tjddjD]\}}|j|tqWdS)NT)Zpernic)r#Znet_io_countersrxr^rb)r%rzr}r'r'r(test_net_io_countersszTestSystem.test_net_io_countersz not supportedcCsFx@tjjD]0\}}|j|tx|D]}|j|jtq(WqWdS)N)r#r=rxr^rblabel)r%ruunitsunitr'r'r(r>s  zTestSystem.test_sensors_fanscCsFx@tjjD]0\}}|j|tx|D]}|j|jtq(WqWdS)N)r#r;rxr^rbr)r%rurrr'r'r(r<s  z$TestSystem.test_sensors_temperaturescCsfx`tjD]T}|j|jt|j|jttdf|j|jttdf|j|jt tdfq WdS)N) r#usersr^rurbrEryhostpidint)r%userr'r'r( test_userss zTestSystem.test_usersN)rUrVrWrX classmethodrirjrqrsrtrZskipIfr rrr rwr|r~rrr>rr<rr'r'r'r(rfs     rfc@s(eZdZdZddZddZddZdd Zd d Zd d Z ddZ ddZ ddZ ddZ ddZddZddZddZddZd d!Zd"d#Zd$d%Zd&d'Zd(d)Zd*d+Zd,d-Zd.d/Zd0d1Zd2d3Zd4d5Zd6d7Zd8d9Zd:d;Z dd?Z"d@dAZ#dBdCZ$dDdEZ%dFdGZ&dHS)ITestFetchAllProcessesz~Test which iterates over all running processes and performs some sanity checks against Process API's returned values. cCsdtr`ddl}ddl}|j}|j}tdd|D|_tdd|D|_tdd|D|_dS)NrcSsg|] }|jqSr')Zpw_uid).0xr'r'r( (sz/TestFetchAllProcesses.setUp..cSsg|] }|jqSr')Zpw_name)rrr'r'r(r)scSsg|] }|jqSr')Zgr_gid)rrr'r'r(r*s) r pwdgrpZgetpwallZgetgrallsetall_uids all_usernamesall_gids)r%rrrgroupsr'r'r(setUp"szTestFetchAllProcesses.setUpcCsd}tdddddddd d d d g }tr6t r6|jd g}x2ttjD]$}|jdrVqF||kr`qF|j|qFWt }g}x(tj D]}|j x|D]}|}ydf} i} t ||d} | dk rt | r|d krtjf} n|dkrddi} | | | }n| }|d7}WnLtk r>d|jjd|} t| Yqtjtjfk r} zJ|j| j|j| jr|j| j|jt| st| jstWYdd} ~ Xqtk rX} zdddd}|d||f7}||kr|dt|7}|d7}|dd7}|dtj7}djdd|j D}|d7}|j|PWYdd} ~ XqX|ddgdd ifkr~|s~t|t ||}|||qWWdQRXqW|r|j!d j||stdS)!NrZ send_signalZsuspendZresumeZ terminatekillwaitZas_dictparentZchildrenr]oneshotr2r}rSZgroupedFz&%r was skipped because not implementedz.test_ =FzFAIL: test_%s (proc=%sz , ret=%s)z) -z %scss|]}d|VqdS) Nz r')rir'r'r( csz7TestFetchAllProcesses.test_fetch_all..g)"rrradddirr#r$ startswithappendobjectZ process_iterrgetattrr r3NotImplementedError __class__rUrZ NoSuchProcessZ AccessDeniedr!rrurbrlmsg Exceptionrepr traceback format_excjoin splitlinesZfail)r%Z valid_procsZexcluded_namesZattrsrudefaultZfailuresproargskwargsattrrerrsmethr'r'r(test_fetch_all,sx             z$TestFetchAllProcesses.test_fetch_allcCs*|j|tx|D]}|j|tqWdS)N)r^listrb)r%rorgpartr'r'r(cmdlinets  zTestFetchAllProcesses.cmdlinecCst|j|ttdf|s&|j|dnJtjj|s:t|trptjj |rpt tdrpt tdrptj |tj sptdS)NraccessX_OK) r^rbryr!r6r7isabsrlr isfiler"rr)r%rorgr'r'r(exeyszTestFetchAllProcesses.execCs|j|t|j|ddS)Nr)r^rrn)r%rorgr'r'r(rs zTestFetchAllProcesses.pidcCs |j|ttf|j|ddS)Nr)r^rrrn)r%rorgr'r'r(ppidszTestFetchAllProcesses.ppidcCs|j|tts|stdS)N)r^rbrrl)r%rorgr'r'r(rus zTestFetchAllProcesses.namec Cs^|j|ty|j|dWn*tk rFtr@|jtjkr@nYnXtj dtj |dS)Nrz%Y %m %d %H:%M:%S) r^rmrnrlrstatusr#Z STATUS_ZOMBIEtimeZstrftimeZ localtime)r%rorgr'r'r( create_times z!TestFetchAllProcesses.create_timecCsDt|s tx2|D]*}|j|t|j|d|j||jqWdS)Nr)rrlr^rrnrar)r%rorgZuidr'r'r(rBs     zTestFetchAllProcesses.uidscCsPt|s tx>|D]6}|j|tt rt r|j|d|j||jqWdS)Nr) rrlr^rr rrnrar)r%rorggidr'r'r(gidss      zTestFetchAllProcesses.gidscCs*|j|t|sttr&|j||jdS)N)r^rbrlr rar)r%rorgr'r'r(usernames zTestFetchAllProcesses.usernamecCs0|j|t|st|j|d|j|tdS)N?)r^rbrlZassertNotEqualrar)r%rorgr'r'r(rs  zTestFetchAllProcesses.statuscCsBt|s tx0|D](}|j|ttf|dkr|j|dqWdS)Nrr)rrlr^rrrn)r%rorgfieldr'r'r(rJs   z!TestFetchAllProcesses.io_counterscCshtr*t|stx|D]}|j|tqWtrL|j|jd|j|jdn|j|d|j |ddS)Nrrr/)rrr/) r rrlr^rrrnZioclassvaluera)r%rorgrr'r'r(rGs   zTestFetchAllProcesses.ionicecCs|j|t|j|ddS)Nr)r^rrn)r%rorgr'r'r( num_threadss z!TestFetchAllProcesses.num_threadscCsr|j|tx`|D]X}t|s"t|j|jd|j|jd|j|jdx|D]}|j|tt fqRWqWdS)Nr) r^rrrlrnidZ user_timeZ system_timerrm)r%rorgtrr'r'r(threadss    zTestFetchAllProcesses.threadscCs6t|s tx$|D]}|j|t|j|dqWdS)Nr)rrlr^rmrn)r%rorgrpr'r'r(rks   zTestFetchAllProcesses.cpu_timescCs0|j|td|kodkns,t|dS)NggY@)r^rmrl)r%rorgr'r'r( cpu_percents z!TestFetchAllProcesses.cpu_percentcCs\|j|ttr|dkrdS|j|dtjdkr@|j|d|j|tt tjdS)Nrrr) r^rrrnr# cpu_countr!rarrange)r%rorgr'r'r(rQs     zTestFetchAllProcesses.cpu_numcCst|s tx(|D] }|j|ttf|j|dqWtrt r|jdkrxx|j D](}|dkrRt ||}|j |j||dqRWnDt r|j|j |j|j|j|j|j|j|j|j|j|jdS)Nrvms)r)rrlr^rrrnr rr_fieldsr assertGreaterr Z peak_wsetZwsetZpeak_paged_poolZ paged_poolZpeak_nonpaged_poolZ nonpaged_poolZ peak_pagefileZpagefile)r%rorgrrur'r'r( memory_infos    z!TestFetchAllProcesses.memory_infocCst|s ttjj}xR|jD]H}t||}|j|tt f|j |d||fd|j |||||fdqWt r~|j |j |jdS)Nr)r)rrlr#Zvirtual_memorytotalrrr^rrrnZassertLessEqualrZpssZuss)r%rorgrrurr'r'r(memory_full_infos    z&TestFetchAllProcesses.memory_full_infocCs|j|tx|D]}|j|jt|j|jttrF|j|jdnhtr|j|j t|j|j t|j|j t|j |j d|j |j d |j|j dntr|j rqtjj|jst|tjj|jst|qWdS) Nrrrrdar+a+r)rrdrrr)r^rfdrr7rbr r!rZpositionmodeflagsrnrarrr6rrlr)r%rorgfr'r'r( open_filess"   z TestFetchAllProcesses.open_filescCs|j|t|j|ddS)Nr)r^rrn)r%rorgr'r'r(rL(s zTestFetchAllProcesses.num_fdscCs2|jt|tt|x|D] }t|qWdS)N)r!lenrr)r%rorgrvr'r'r( connections,s z!TestFetchAllProcesses.connectionscCs|r|j|ttjj|s$t|ytj|}WnDtk rv}z(trX|j t j j krXn|j t j krfWYdd}~XnXtj|jstdS)N)r^rbr6r7rrlstatOSErrorr errnor#Z _psplatformZACCESS_DENIED_SETENOENTS_ISDIRst_mode)r%rorgstrr'r'r(cwd1s   zTestFetchAllProcesses.cwdcCs0|j|td|kodkns,t|dS)Nrd)r^rmrl)r%rorgr'r'r(memory_percentAs z$TestFetchAllProcesses.memory_percentcCs|j|tdS)N)r^bool)r%rorgr'r'r( is_runningEsz TestFetchAllProcesses.is_runningcCsR|j|t|gkst|ttj}x$|D]}|j|t|j||q.WdS)N)r^rrlrr#rrra)r%rorgZcpusrpr'r'r(r Hs     z"TestFetchAllProcesses.cpu_affinitycCsH|j|ttdf|dk rDtjj|s0t|tjj|sDt|dS)N)r^rbryr6r7rrlr8)r%rorgr'r'r(rEPszTestFetchAllProcesses.terminalcCsx|D]}|j|jt|j|jt|j|jtxr|jD]h}t||}|dkrv|jdstjj |jst |jq<|dkr|st q<|j|t t f|j |dq.i)r^rr rlrr#ra)r%rorgZ prioritiesr'r'r(nicems  "zTestFetchAllProcesses.nicecCs:t|s tx(|D] }|j|ttf|j|dqWdS)Nr)rrlr^rrrn)r%rorgrr'r'r(num_ctx_switchesvs  z&TestFetchAllProcesses.num_ctx_switchescCs@|j|t|jt|d|j|dd|j|dddS)Nr/rrrr)r^tupler!rrn)r%rorgr'r'r(r2|s zTestFetchAllProcesses.rlimitcCs>|j|tx,|jD] \}}|j|t|j|tqWdS)N)r^dictrxrb)r%rorgrrvr'r'r(r@s  zTestFetchAllProcesses.environN)'rUrVrWrXrrrrrrrurrBrrrrJrGrrrkrrQrrrrLrrrrr rErSrNrrr2r@r'r'r'r(rsH H      r__main__)/rXrr6rrrr[ contextlibrr#rrrrrrr r r r Zpsutil._compatr rZ psutil.testsrrrrrrrrrrrrrrrrZTestCaserrYrfrrU__file__r'r'r'r( sX                             x^n PK!t_881__pycache__/test_connections.cpython-36.opt-1.pycnu[3 JZP@s8dZddlZddlZddlZddlmZddlmZddlmZddlmZddlm Z ddl Z ddl m Z dd l m Z dd l m Z dd l mZdd l mZdd l mZddl mZddl mZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddlm$Z$ddlm%Z%dd lm&Z&dd!lm'Z'dd"lm(Z(dd#lm)Z)dd$lm*Z*e j+Z,Gd%d&d&e-Z.Gd'd(d(e.e'j/Z0Gd)d*d*e.e'j/Z1Gd+d,d,e.e'j/Z2Gd-d.d.e'j/Z3e4d/kr4e!e5dS)0z;Tests for net_connections() and Process.connections() APIs.N)closing)AF_INET)AF_INET6) SOCK_DGRAM) SOCK_STREAM)FREEBSD)LINUX)NETBSD)OPENBSD)OSX)POSIX)SUNOS)WINDOWS) supports_ipv6)PY3)AF_UNIX) bind_socket)bind_unix_socket)check_connection_ntuple)create_sockets) get_free_port)HAS_CONNECTIONS_UNIX)pyrun) reap_children)run_test_module_by_name) safe_rmpath)skip_on_access_denied)tcp_socketpair)TESTFN)TRAVIS)unittest)unix_socket_path)unix_socketpair) wait_for_filec@s8eZdZddZddZddZd dd Zdd d ZdS)BasecCststjdd}dS)Nall)kind)r thisproc connections)selfconsr+(/usr/lib64/python3.6/test_connections.pysetUp6s z Base.setUpcCs"ttttstjdd}dS)Nr%)r&)rrrr r'r()r)r*r+r+r,tearDown<s  z Base.tearDowncCsrtjdd}tdd|D}tr.||jS|jt|d|djdkrf|j||jj|j|dSdS)Nr%)r&cSsg|]}|j|fqSr+)fd).0cr+r+r, Gsz+Base.get_conn_from_sock..r)r'r(dictr fileno assertEquallenr/)r)sockr*Zsmapr+r+r,get_conn_from_sockEs  zBase.get_conn_from_sockNcCs|dkr|j|}t||jdkr6|j|j|j|j|j|j|j|j|jtj tj |j }| rt rt |tr|j}|jtkr|dd}|jtkrtrn|j|j||jtkrtrtjdd}|jtj||S)zGiven a socket, makes sure it matches the one obtained via psutil. It assumes this process created one connection only (the one supposed to be checked). Nr3r%)r&r4)r:rr/r7r6familytypeZ getsockoptsocketZ SOL_SOCKETZSO_TYPEZ getsocknamer isinstancebytesdecoderrr laddrrr'r(compare_procsys_connectionsosgetpid)r)r9connrBr*r+r+r, check_socketRs(     zBase.check_socketr%c sdytj|d}Wn tjk r0tr*dSYnXfdd|D}|j|j|j||dS)zGiven a process PID and its list of connections compare those against system-wide connections retrieved via psutil.net_connections. )r&Ncs"g|]}|jkr|ddqS)Nr3r4)pid)r0r1)rHr+r,r2sz4Base.compare_procsys_connections..)psutilnet_connectionsZ AccessDeniedr sortr7)r)rHZ proc_consr&Zsys_consr+)rHr,rCvsz Base.compare_procsys_connections)N)r%)__name__ __module__ __qualname__r-r.r:rGrCr+r+r+r,r$4s   $r$c@s|eZdZdZddZeje dddZddZ eje dd d Z eje d d d Z eje d ddZ dS)TestUnconnectedSocketsz;Tests sockets which are open but not connected to anything.c CsFdtf}tttt|d }|j|}|j|jtj WdQRXdS)Nz 127.0.0.1)addr) rrrrrrGr7statusrI CONN_LISTEN)r)rPr9rFr+r+r, test_tcp_v4s  z"TestUnconnectedSockets.test_tcp_v4zIPv6 not supportedc CsFdtf}tttt|d }|j|}|j|jtj WdQRXdS)Nz::1)rP) rrrrrrGr7rQrIrR)r)rPr9rFr+r+r, test_tcp_v6s  z"TestUnconnectedSockets.test_tcp_v6c CsFdtf}tttt|d }|j|}|j|jtj WdQRXdS)Nz 127.0.0.1)rP) rrrrrrGr7rQrI CONN_NONE)r)rPr9rFr+r+r, test_udp_v4s  z"TestUnconnectedSockets.test_udp_v4c CsFdtf}tttt|d }|j|}|j|jtj WdQRXdS)Nz::1)rP) rrrrrrGr7rQrIrU)r)rPr9rFr+r+r, test_udp_v6s  z"TestUnconnectedSockets.test_udp_v6z POSIX onlycCsLt<}tt|td }|j|}|j|jtjWdQRXWdQRXdS)N)r=) r!rrrrGr7rQrIrU)r)namer9rFr+r+r, test_unix_tcps z$TestUnconnectedSockets.test_unix_tcpcCsLt<}tt|td }|j|}|j|jtjWdQRXWdQRXdS)N)r=) r!rrrrGr7rQrIrU)r)rXr9rFr+r+r, test_unix_udps z$TestUnconnectedSockets.test_unix_udpN)rLrMrN__doc__rSr skipIfrrTrVrWr rYrZr+r+r+r,rOsrOc@sTeZdZdZejedddZeje dddZ e e dd d Z d d Z d S)TestConnectedSocketPairszJTest socket pairs which are are actually connected to each other. zunreliable on SUONSc Cszdtf}tt|d\}}zHtjdd}|jt|d|j|djtj |j|djtj Wd|j |j XdS)Nz 127.0.0.1)rPtcp4)r&r;rr3) rrrr'r(r7r8rQrIZCONN_ESTABLISHEDclose)r)rPserverclientr*r+r+r,test_tcps  z!TestConnectedSocketPairs.test_tcpz POSIX onlycCs2t }t|\}}ztjdd}tr6dd|D}|jt|dtsRtsRt r|j|dj d|j|dj d|j||dj p|dj nzt rxt|dj |dj |dj |dj fD]}|j|dqWn:|j|dj p|dj ||j|dj p|dj |Wd|j |j XWdQRXdS) Nunix)r&cSsg|]}|jdkr|qS)z /var/run/log)raddr)r0r1r+r+r,r2sz6TestConnectedSocketPairs.test_unix..r;rr3)r!r"r'r(r r7r8rrr rdrBr r_)r)rXr`rar*rPr+r+r, test_unixs&    "z"TestConnectedSocketPairs.test_unix)Zonly_ifcsfdd}tjd}tjd}ddlm}tjjt}||jt t d|d}||jt t d|d}||jt t d |d}||jt t d |d} t |} t t|} t |} t t|} trt |}t t|}t | }t t|}nd}d}d}d}xtjD]}|j}jt|d x|D]}|j| jkr\|||t t| ftjdn|j| jkr|||t t| ftjdnZ|jt|ddkr|||t t|ftjdn,|jt|ddkr0|||t t|ftjdq0Wq Wjt|jdddS)Nc sd }t|j|j|j|j|j|j|j|j|j|j|x"|D]} |j| d } | |krXqXqXWtrj |j |gdS) Nr%inetinet4inet6tcpr^tcp6udpudp4udp6)r&) r%rgrhrirjr^rkrlrmrn) rr7r<r=rBrdrQr(rrCrH) procrFr<r=rBrdrQZkindsZ all_kindsr&r*)r)r+r, check_conns  z8TestConnectedSocketPairs.test_combos..check_conna import socket, time s = socket.socket($family, socket.SOCK_STREAM) s.bind(('$addr', 0)) s.listen(1) with open('$testfn', 'w') as f: f.write(str(s.getsockname()[:2])) time.sleep(60) z import socket, time s = socket.socket($family, socket.SOCK_DGRAM) s.bind(('$addr', 0)) with open('$testfn', 'w') as f: f.write(str(s.getsockname()[:2])) time.sleep(60) r)Templatez 127.0.0.1)r<rPZtestfnz::1r3r%rgrhrjr^rlrmrHrirkrnz???)r&)r%rgrhrjr^)r%rgrhrlrm)r%rgrirjrk)r%rgrirlrn)textwrapdedentstringrqrDpathbasenamerZ substituteintrrrevalr#rr'Zchildrenr(r7r8rHrrIrRrrUgetattr assertRaises ValueError)r)rpZ tcp_templateZ udp_templaterqZtestfileZ tcp4_templateZ udp4_templateZ tcp6_templateZ udp6_templateZ tcp4_procZ tcp4_addrZ udp4_procZ udp4_addrZ tcp6_procZ tcp6_addrZ udp6_procZ udp6_addrpr*rFr+)r)r, test_combossb       z$TestConnectedSocketPairs.test_combosc Cst}tjdd}|jt|t|tjdd}|jt|trJdndx,|D]$}|j|jtt f|j|j t qVWtjdd}|jt|d|j|djt|j|dj t trtjdd}|jt|d|j|djt |j|dj t tjd d}|jt|tr(dndx.|D]&}|j|jtt f|j|j t q4Wtjd d}|jt|d|j|djt|j|dj t trtjd d}|jt|d|j|djt |j|dj t tjd d}|jt|trd ndx2|D]*}|j|jtt f|j|j t t fqWtrtjdd}|jt|dx.|D]&}|j|jt |j|j t t fqlWt rtjdd}|jt|dx.|D]&}|j|jt|j|j t t fqWWdQRXdS)Nr%)r&rjr;r3r^rrkrlrmrnrgrirc)rr'r(r7r8rassertInr<rrr=rrrr)r)socksr*rFr+r+r,test_multi_sockets_filteringes`                z5TestConnectedSocketPairs.test_multi_sockets_filteringN)rLrMrNr[r r\r rbr rfrr r}rr+r+r+r,r]s !br]c@sJeZdZdZeddZeddZeeje o6e dddZ d S) TestSystemWideConnectionszTests for net_connections().c sfdd}tddlm}xZ|jD]N\}}|dkrBt rBq*|\}}tj|}jt|tt |||||q*Wj t tjddWdQRXdS)NcsVttdt}xB|D]:}j|j||d|j|krFj|j||dt|qWdS)Nr)msg)ryr>objectrr<r=r)r*familiestypes_rrF)r)r+r,checks   z0TestSystemWideConnections.test_it..checkr) conn_tmaprcz???)r&) rpsutil._commonritemsrrIrJr7r8setrzr{)r)rrr&groupsrrr*r+)r)r,test_its   z!TestSystemWideConnections.test_itc Cs@t0}ddtjddD}|jt|t|WdQRXdS)NcSsg|]}|jtjkr|qSr+)rHrDrE)r0xr+r+r,r2sz>TestSystemWideConnections.test_multi_socks..r%)r&)rrIrJr7r8)r)rr*r+r+r,test_multi_sockssz*TestSystemWideConnections.test_multi_sockszunreliable on OSX + TRAVISc st}t|}WdQRXgd}xRt|D]F}tjjtt|}tj d|}t |}j |j |j t|q,Wx$t|D]}tt|}t|qWfddtjddD}xJD]B|jtfdd|D|tj} |jt| jd|qWdS)N a import time, os from psutil.tests import create_sockets with create_sockets(): with open('%s', 'w') as f: f.write(str(os.getpid())) time.sleep(60) csg|]}|jkr|qSr+)rH)r0r)pidsr+r,r2szFTestSystemWideConnections.test_multi_sockets_procs..r%)r&csg|]}|jkr|qSr+)rH)r0r)rHr+r,r2s)rr8rangerDrurealpathrstrrrrsrappendrHZ addCleanuprr#rIrJr7Processr() r)rZexpectedtimesiZfnamesrcZsprocZsysconsr|r+)rHrr,test_multi_sockets_procss(       z2TestSystemWideConnections.test_multi_sockets_procsN) rLrMrNr[rrrr r\r rrr+r+r+r,rs rc@seZdZddZdS)TestMisccCsg}g}xXttD]L}|jdrtt|}t|}|jt||j|||j||j|qWtrrtjtj t r|tj dS)NZCONN_) dirrI startswithryrZ assertNotInrr Z CONN_IDLEZ CONN_BOUNDrZCONN_DELETE_TCB)r)ZintsZstrsrXZnumZstr_r+r+r,test_connection_constantss     z"TestMisc.test_connection_constantsN)rLrMrNrr+r+r+r,rsr__main__)6r[rDr>rr contextlibrrrrrrIrrr r r r r rrrZpsutil._compatrZ psutil.testsrrrrrrrrrrrrrrrr r!r"r#rr'rr$ZTestCaserOr]rrrL__file__r+r+r+r,s^                                  \7`P PK!y\PP'__pycache__/test_process.cpython-36.pycnu[3 JZ9@sdZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl Z ddlZddlmZddlmZddlmZddlmZddlmZddlmZdd lmZdd lmZdd lmZdd lmZdd lmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddlm$Z$ddlm%Z%ddlm&Z&ddlm'Z'ddlm(Z(ddlm)Z)ddlm*Z*ddlm+Z+ddlm,Z,ddlm-Z-dd lm.Z.dd!lm/Z/dd"lm0Z0dd#lm1Z1dd$lm2Z2dd%lm3Z3dd&lm4Z4dd'lm5Z5dd(lm6Z6dd)lm7Z7dd*lm8Z8dd+lm9Z9dd,lm:Z:dd-lm;Z;dd.lmZ?erej@dkrGd2d3d3e?ZAGd4d5d5e;j>ZBeCd6kre2eDdS)7zTests for psutil.Process class.N)AIX)BSD)LINUX)NETBSD)OPENBSD)OSX)POSIX)SUNOS)WINDOWS)long)PY3)APPVEYOR) call_until)copyload_shared_lib) create_exe)create_proc_children_pair)create_zombie_proc)enum)get_test_subprocess) get_winver)HAS_CPU_AFFINITY) HAS_ENVIRON) HAS_IONICE)HAS_MEMORY_MAPS)HAS_PROC_CPU_NUM)HAS_PROC_IO_COUNTERS) HAS_RLIMIT) HAS_THREADS)mock)PYPY) PYTHON_EXE) reap_children)retry_before_failing)run_test_module_by_name) safe_rmpath)sh)skip_on_access_denied)skip_on_not_implemented)TESTFILE_PREFIX)TESTFN) ThreadTask)TRAVIS)unittest) wait_for_pid) WIN_VISTAc@sreZdZdZddZddZddZdd Zd d Zd d Z ddZ ddZ ddZ ddZ ddZddZddZeje dddZdd Zeje d!ejed"d#d$Zeje deed%d&d'Zeje dejeoee kdd(d)Z!eje dejeoee kdd*d+Z"eje# dd,d-Z$eje# dd.d/Z%eje# dd0d1Z&eje# dd2d3Z'eje# dd4d5Z(d6d7Z)eje d8d9d:Z*eje+ dd;d<Z,e-e.e/d%eje+ dd=d>Z0d?d@Z1dAdBZ2eje3 ddCdDZ4eje3 ddEdFZ5dGdHZ6dIdJZ7dKdLZ8dMdNZ9dOdPZ:eje;dQejeeje d!dWdXZ?dYdZZ@d[d\ZAd]d^ZBd_d`ZCdadbZDejeE ddcddZFejeE ddedfZGejeE ddgdhZHejeIdiejeJdjdkdlZKejeIdiejeJdjdmdnZLeje d!dodpZMeed%ejeNpzeOdqdrdsZPdtduZQdvdwZRdxdyZSdzd{ZTd|d}ZUd~dZVddZWddZXddZYddZZddZ[ddZ\eje d!ddZ]eje d!ddZ^eje d!ddZ_ddZ`ejea dddZbejea deje d!ddZcdS) TestProcesszTests for psutil.Process class.cCs ttdS)N)r$r))selfr1$/usr/lib64/python3.6/test_process.pysetUpNszTestProcess.setUpcCs tdS)N)r!)r0r1r1r2tearDownQszTestProcess.tearDownc CsXtj}|j|jtjt}|jtj|jj|j|jt d|_WdQRXdS)N!) psutilProcess assertEqualpidosgetpidr assertRaisesAttributeError)r0psprocr1r1r2test_pidTs  zTestProcess.test_pidcCsNt}|j}tj|}|j|j}|jtj|trJ|j |t j dS)N) rr9r6r7killwait assertFalse pid_existsrr8signalSIGKILL)r0r?r@r>sigr1r1r2 test_kill\s zTestProcess.test_killcCsNt}|j}tj|}|j|j}|jtj|trJ|j |t j dS)N) rr9r6r7 terminaterBrCrDrr8rESIGTERM)r0r?r@r>rGr1r1r2test_terminatefs zTestProcess.test_terminatec CsLtr tjntj}t}tj|j}|j||j }|j tj |jtrH|j || t}tj|j}|j|t jdttjdd(|jtj|j|WdQRXWdQRXt}tj|j}|j|t jdttjdd,|jtjtjj|WdQRXWdQRXdtjkrHtjd}|jt|jtjdS)Nzpsutil.os.kill) side_effectr)rrErFrJrr6r7r9 send_signalrBrCrDr8rpatchOSErrorerrnoZESRCHr< NoSuchProcessZEPERM AccessDeniedpids ValueError)r0rGr?r>Zexit_sigr1r1r2test_send_signalps2      " zTestProcess.test_send_signalcCs^t}tj|j}|j|j}tr8|j|tj n|j|tj |j |j t}tj|j}|j |j}tr|j|tj n|j|tj |j |j d}ttd|g}tj|j}|j|jd|j |j ttd|g}tj|j}|j|jd|j|jdt}tj|j}|j|jtj|jd|jt|jddS)Nz0import time, sys; time.sleep(0.01); sys.exit(5);z-cg{Gz?)rWN)rr6r7r9rArBrr8rErFrJrC is_runningrIr assertInnamer<TimeoutExpiredrU)r0r?r>coder1r1r2 test_waits<     zTestProcess.test_waitcCst\}}|jtj|jd|jtj|jd|j|j|j}|j}trp|j|tj |j|dn|j|tj |j|tj dS)Ng{Gz?) rr<r6r]rBrIrr8rErJ)r0p1p2Zret1Zret2r1r1r2test_wait_non_childrens z"TestProcess.test_wait_non_childrenc Cst}tj|j}|jtj|jd|jtjd}x:y|jd}Wn$tjk rltj|krhYq:XPq:Wt r|j |t j n|j |t j |j|jdS)Nr)rr6r7r9r<r]rBrAtimerr8rErFrJrCrZ)r0r?r>Zstop_atr^r1r1r2test_wait_timeout_0s    zTestProcess.test_wait_timeout_0c Cstj}|jdd|jddxRtdD]F}|jdd}|j|t|j|dtsd|j|dq*|j|dq*W|j t |jddWdQRXdS)NgMbP?)ZintervaldggY@rXrY) r6r7 cpu_percentrangeassertIsInstancefloatassertGreaterEqualrassertLessEqualr<rU)r0r>xZpercentr1r1r2test_cpu_percents      zTestProcess.test_cpu_percentc Cs4tjddd}tjj|js&tWdQRXdS)Nzpsutil.cpu_count)Z return_value)rrOr6r7rgcalledAssertionError)r0mr1r1r2test_cpu_percent_numcpus_nones z)TestProcess.test_cpu_percent_numcpus_nonecCsxtjj}|jdks(|jdks(t||jdks:t||jdksLt|x&|jD]}t j dt j t ||qTWdS)Ngz%H:%M:%S) r6r7 cpu_timesusersystemrp children_userchildren_system_fieldsrdstrftime localtimegetattr)r0timesr\r1r1r2test_cpu_timess   zTestProcess.test_cpu_timescCstjjdd\}}tjdd\}}t||gt||gdkrZ|jd||ft||gt||gdkr|jd||fdS)Nrcg?zexpected: %s, found: %s)r6r7rsr:r|maxminfail)r0 user_timeZ kernel_timeutimeZktimer1r1r2test_cpu_times_2s zTestProcess.test_cpu_times_2z not supportedcCsPtj}|j}|j|dtjdkr4|j|d|j|jttjdS)NrrX)r6r7Zcpu_numrk cpu_countr8r[rh)r0r>Znumr1r1r2 test_cpu_nums    zTestProcess.test_cpu_numcCsdt}tj}tj|j}|j}t||}|dkrJ|jd|||ftjdtj |jdS)Nrcz'expected: %s, found: %s, difference: %sz%Y %m %d %H:%M:%S) rrdr6r7r9 create_timeabsrryrz)r0r?Znowr>r differencer1r1r2test_create_times  zTestProcess.test_create_timez POSIX onlyznot reliable on TRAVIScCsLtjj}tjjs tjjr>tjj t d}|j ||n |j |dS)Ntty) r6r7terminalsysstdinisattystdoutr:pathrealpathr%r8 assertIsNone)r0rrr1r1r2 test_terminal-s  zTestProcess.test_terminal)Zonly_ifcCstj}|j}ttd}|jWdQRX|j}t rt r|j|j |j |j |j |j t r|j|j |j |j |j|jn |j|j|j|j|j|j|j}tjtd.}tr|jtdddn|jddWdQRX|j}|j|j |j |j|j|j|j|j |j |j|j|jt r^|j|j|j|j|j |j xJtt|D]:}tr|dkrql|j||d|j||dqlWdS)Nrb)prefixrmi@Basciircr)r6r7Z io_countersopenr readrr assertGreaterZ read_countr8Z write_countrZ read_charsZ write_charsrkZ read_bytesZ write_bytestempfileZ TemporaryFiler(r writebytesrhlen)r0r>Zio1fZio2ir1r1r2test_io_counters7s>  zTestProcess.test_io_countersc CstrZioclassvalueoriginalr1r1r2 test_ionicecsJ                      zTestProcess.test_ionicecCst}tj|j}tr|jt|jdd|jt|jdd |jt|jd|jt|jdd|j td|jtj d|j td|jtj d|j td|jdd n"|jt|jd |jt|jdddS) Nrc rXrfooz*can't specify value with IOPRIO_CLASS_NONEz*can't specify value with IOPRIO_CLASS_IDLEz$'ioclass' argument must be specified)rrrY) rr6r7r9rr<rUr TypeErrorZassertRaisesRegexrr)r0r?r>r1r1r2test_ionice_errss$ zTestProcess.test_ionice_errscCsddl}tjtj}ddttD}|s4t|x|D]}tt|}|j|d|t|kr|j |t||t rxq:|j |j ||j |q:|j |}|j t |d|j|dd|j|ddq:WdS)NrcSsg|]}|jdr|qS)ZRLIMIT) startswith).0rmr1r1r2 sz/TestProcess.test_rlimit_get..rcrXrYrY)resourcer6r7r:r;dirrpr{rkr8rrlimitZ getrlimitr)r0rr>namesr\rretr1r1r2test_rlimit_gets       zTestProcess.test_rlimit_getcCst}tj|j}|jtjd|j|jtjd|jttj jdjdWdQRX|jt|jtjdWdQRXdS)NrWr)rWrW)rWrW)rWrWrW) rr6r7r9r RLIMIT_NOFILEr8r<rUZ _psplatform)r0r?r>r1r1r2test_rlimit_sets   zTestProcess.test_rlimit_setc Cstj}|jtj\}}z|jtjd|fttd}|jddWdQRX|jt*}ttd}|jddWdQRXWdQRX|j t r|j j n|j dt j Wd|jtj||f|j |jtj||fXdS)NiwbXir)r6r7r RLIMIT_FSIZErr)rr<IOErrorr8r Z exceptionrQZEFBIG)r0r>softhardrexcr1r1r2 test_rlimits   " zTestProcess.test_rlimitcCstj}|jtj\}}zN|jtjd|f|jtjtj|fttd}|jddWdQRXWd|jtj||f|j|jtj||fXdS)Nirri) r6r7rr RLIM_INFINITYrr)rr8)r0r>rrrr1r1r2test_rlimit_infinitys z TestProcess.test_rlimit_infinitycCs<tj}|jtj\}}|jtj||jtj||fdS)N)r6r7rrr8r)r0r>rrr1r1r2test_rlimit_infinity_valuesz&TestProcess.test_rlimit_infinity_valuecCsrtj}trstep1step2r1r1r2test_num_threadss zTestProcess.test_num_threadsz WINDOWS onlycCstj}|j|jddS)Nr)r6r7rZ num_handles)r0r>r1r1r2test_num_handles szTestProcess.test_num_handlescCstj}trrrZathreadr1r1r2 test_threadss  zTestProcess.test_threadsc Cst}tj|j}trDy |jWn tjk rBtjdYnX|j |j j t dd|jDdd|j |j j t dd|jDdddS)Nz$on OpenBSD this requires root accesscSsg|] }|jqSr1)r)rrmr1r1r2r7sz.TestProcess.test_threads_2..g?)ZdeltacSsg|] }|jqSr1)r)rrmr1r1r2r:s)rr6r7r9rrrSr,rZassertAlmostEqualrsrtsumru)r0r?r>r1r1r2test_threads_2)s   zTestProcess.test_threads_2c Cstj}|jdd\}}|j}|j|d|j|ddgd}|jdd\}}|j}|j|||j|||j||~tr|j} |j| j| j |j| j | j |j} x | j D]} |jt | | dqWdS)Nrcri`)r6r7Z memory_infomemory_percentrrkr r8ZrssZwsetvmsZpagefilerxr{) r0r>Zrss1Zvms1Zpercent1ZmemarrZrss2Zvms2Zpercent2memr\r1r1r2test_memory_info<s&       zTestProcess.test_memory_infocCstjj}tjj}xB|jD]8}t||}|j|d||fd|j|||||fdqWt sft sft rt|j|j dt r|j|j d|j|jddS)Nr)msg)r6Zvirtual_memorytotalr7Zmemory_full_inforxr{rkrlrr russZpssZswap)r0rrr\rr1r1r2test_memory_full_infoZs     z!TestProcess.test_memory_full_infoc Cstj}|j}dd|D}|jt|tt||jdd}x|D]}|jjdsHtjj |jspt |jt ry*tjj |jstjj |jst |jWnHt k rtsn,td}|j}WdQRXd|j|krYnXqHdtjj|jkrHtjj |jsHt |jqHWxv|D]n}xf|jD]\}t||} |d krHq*n<|d krb| st | n"|j| ttf| d ks*t | q*WqWdS)NcSsg|]}|qSr1r1)rrmr1r1r2rksz0TestProcess.test_memory_maps..F)Zgrouped[z/proc/self/smapsz %s (deleted)Z64raddrpermsr)rr)r6r7 memory_mapsr8rsetrrr:isabsrprexistsislinkrrrbasenamerxr{rirr ) r0r>mapspathsZext_mapsntrdataZfnamerr1r1r2test_memory_mapsgs<          zTestProcess.test_memory_mapsc sHt8}ddfddtjjD}|j||WdQRXdS)NcSstjjtjj|S)N)r:rrnormcase)r>r1r1r2normpathsz8TestProcess.test_memory_maps_lists_lib..normpathcsg|]}|jqSr1)r)rrm)rr1r2rsz:TestProcess.test_memory_maps_lists_lib..)rr6r7rr[)r0rZlibpathsr1)rr2test_memory_maps_lists_libs  z&TestProcess.test_memory_maps_lists_libcCstj}|j}d|ko"dkns0t||jdd}d|koNdkns\t|d|kondkns|t||jt|jddtststr|jdd}d|kodknst|d|kodknst|dS)Nrrfr)Zmemtypez?!?r) r6r7rrpr<rUrrr )r0r>rr1r1r2test_memory_percents       zTestProcess.test_memory_percentcCsZt}tj|j}|jst|js*t|j|j|j sHt|j sVtdS)N)rr6r7r9rZrprArB)r0r?r>r1r1r2test_is_runnings   zTestProcess.test_is_runningcCst}tj|jj}y|j|tWntk rtrht |t tkrht j j }|j|||tnNdt jdt jdf}y |j|j|dtj|dWntk rYnXYnXt|ddg}|j|ddS)Nz%s.%srrXrLz-czimport os; print('hey')Zhey)rr6r7r9exer8r rpr rr:rrr version_inforeplacer%)r0r?rrZveroutr1r1r2test_exes  zTestProcess.test_exec Cstddg}t|}y(|jdjtj|jjdj|Wn@tk rzt sVt sVt rt|jtj|jjdtnYnXdS)Nz-czimport time; time.sleep(60) r) r rr8joinr6r7r9cmdlinerprrr)r0rr?r1r1r2 test_cmdlines  zTestProcess.test_cmdlinecCsPtt}tj|jjj}tjj tjj t j j}|j |sLt||fdS)N)rr r6r7r9r\lowerr:rrrr executablerrp)r0r?r\Zpyexer1r1r2 test_nameszTestProcess.test_namezbroken on SUNOSz broken on AIXcsfdd}tdt|j|ddddddg}t|}tj|j}trZt|j|j |j ||j |j t j j|j t j j|jt j jdS) Nc s&y tWntk r YnXdS)N)r$rPr1) funky_pathr1r2rms z.TestProcess.test_prog_w_funky_name..rmz foo bar )z-cz9import time; [time.sleep(0.01) for x in range(3000)];arg1Zarg2rLZarg3)r)r addCleanuprr6r7r9r+r-r8rr\r:rrrr)r0rrr?r>r1)rr2test_prog_w_funky_names     z"TestProcess.test_prog_w_funky_namecCsXtj}|j\}}}|j|tj|j|tjttdrT|jtj|jdS)N getresuid) r6r7uidsr8r:getuidgeteuidhasattrr)r0r>real effectivesavedr1r1r2 test_uidss  zTestProcess.test_uidscCsXtj}|j\}}}|j|tj|j|tjttdrT|jtj|jdS)Nr) r6r7gidsr8r:getgidgetegidr getresgid)r0r>rrrr1r1r2 test_gidss  zTestProcess.test_gidscCstj}|jt|jdtrz||j}tjdkr@|j|t j n |j|t |j |tj |jtj|j |jtj|jtj |j |jtj Wd|jtj Xn|j}zyttdr|j tjtjtj|j|jd|j |jdttdr"|j tjtjtj|jtsB|jd|j |jdWntjk r\YnXWdy|j|Wntjk rYnXXdS)Nstrrr getpriorityrXr)rr)r6r7r<rnicer rrrirrrr8NORMAL_PRIORITY_CLASSZHIGH_PRIORITY_CLASSrr:r PRIO_PROCESSr;rrS)r0r>ZinitZ first_nicer1r1r2 test_nice"sB         zTestProcess.test_nicecCstj}|j|jtjdS)N)r6r7r8statusZSTATUS_RUNNING)r0r>r1r1r2 test_statusKszTestProcess.test_statuscCsnt}tj|j}|j}trZ|jd\}}|j|tj dt j krj|j|t j dn|j|tj dS)N\Z USERDOMAIN) rr6r7r9usernamer splitr8getpassZgetuserr:environ)r0r?r>rZdomainr1r1r2 test_usernameOs  zTestProcess.test_usernamecCs*t}tj|j}|j|jtjdS)N)rr6r7r9r8cwdr:getcwd)r0r?r>r1r1r2test_cwd[s zTestProcess.test_cwdcCs.tddg}t|}tj|j}t|jddS)Nz-cz/import os, time; os.chdir('..'); time.sleep(60)z#ret == os.path.dirname(os.getcwd()))r rr6r7r9rr)r0cmdr?r>r1r1r2 test_cwd_2`s  zTestProcess.test_cwd_2cCstj}|j}|st||j|j|ttdrL|j|ttj |j |jt |t t |tt t tjdd}xzts|n|D]j}|j|g|j|j|gttdr|j|jttj |j t|dr|j|jd|jqW|jgtr |j|j|jjn|j|j|ttdrX|j|jttj |j |jt|jd|j||jt ||jt|dS)Nsched_getaffinityT)percpunum_cpurrX)r6r7 cpu_affinityrprrr:r8listr r9rrrhrgr+r"r_procZ_get_eligible_cpusr<rtuple)r0r>initialZall_cpusnr1r1r2test_cpu_affinitygs6          zTestProcess.test_cpu_affinitycCszt}tj|j}ttjdddg}|jt|j||jt|jt dd|jt |jddg|jt|jdd gdS) NT)r!ri'i*r1rXrY) rr6r7r9rrsr<rUr#rhr)r0r?r>Z invalid_cpur1r1r2test_cpu_affinity_errss z"TestProcess.test_cpu_affinity_errscCstj}|j}|st||j|j|g}xBtdt|dD],}x&tj||D]}|rT|j t |qTWqBWx&|D]}|j||j |j|qxWdS)NrrX) r6r7r#rprrhr itertools combinationsappendr$r8)r0r>r'ZcomboslZsubsetZcombor1r1r2"test_cpu_affinity_all_combinationss   z.TestProcess.test_cpu_affinity_all_combinationsz broken on BSDzunreliable on APPVEYORc CsRtj}|j}|jt|kttdn}|jdd|jt|jdt |}x<|D]"}|j tkrZt rz|j |j dPqZW|jdt|WdQRXx"|D]}tj j|j st|qWdt}ttd|g}tj|j}xDtdD],}d d |jD}t|krPtjd qW|jt|x$|D]}tj j|s.t|q.WdS) Nrxizlen(ret) != %izno file found; files=%sz2import time; f = open(r'%s', 'r'); time.sleep(60);z-crfcSsg|] }|jqSr1)r)rrmr1r1r2rsz/TestProcess.test_open_files..g{Gz?)r6r7 open_filesrCr)rrflushrrrrr8Zpositionrreprr:isfilerprr r9rhrdsleepr[) r0r>filesrfilerr?rm filenamesr1r1r2test_open_filess4        zTestProcess.test_open_filesc Csttd}tj}xB|jD] }|j|jks<|j|jkrPqW|j dt |j|j |j|jt r||j |jdn|j |j|j|jd}|j |d|j|j |d|j|j |j|jWdQRXdS)Nwzno file found; files=%srXrrY)rr)r6r7r2rr\fdfilenorr4r8r assertNotIn)r0Zfileobjr>r8Zntupler1r1r2test_open_files_2s  zTestProcess.test_open_files_2cCstj}|j}ttd}|j|j|j|j|dtj}|j|j|j|j|d|j|j|j|j|dS)Nr;rXrc) r6r7Znum_fdsrr)rcloser8socket)r0r>startr8Zsockr1r1r2 test_num_fdss   zTestProcess.test_num_fdsz not reliable on OPENBSD & NETBSDcCsLtj}t|j}x(tdD]}t|j}||krdSqW|jddS)Ni z7num ctx switches still the same after 50.000 iterations)r6r7rZnum_ctx_switchesrhr)r0r>Zbeforermafterr1r1r2test_num_ctx_switchess  z!TestProcess.test_num_ctx_switchescCsttdr"|jtjjtjtj}t}tj|j }|j|j|t ddt r^dSx2tj D]&}|j |j krzqh|j |j||dqhWdS)NgetppidT) recursive)r)rr:r8r6r7ppidrFr;rr9r!r process_iterassertNotEqual)r0 this_parentr?r>r1r1r2 test_ppids    zTestProcess.test_ppidcCs0tj}t}tj|j}|j|jj|dS)N)r:r;rr6r7r9r8parent)r0rKr?r>r1r1r2 test_parents zTestProcess.test_parentc CsFt}tj|j}tjdtjddd|j|jWdQRXdS)Nzpsutil.Processrr)rM) rr6r7r9rrOrRrrM)r0r?r>r1r1r2test_parent_disappeared s  z#TestProcess.test_parent_disappearedcCstj}|j|jg|j|jddgtdd}|j}|jdd}xL||fD]@}|jt|d|j|dj|j|j|djtj qTWdS)NT)rGr)Z creationflagsrX) r6r7r8childrenrrr9rHr:r;)r0r>r?Z children1Z children2rPr1r1r2 test_children(s  zTestProcess.test_childrencCsdt\}}tj}|j|j|g|j|jdd||g|j|j|j|jddgdS)NT)rG)rr6r7r8rPrIrB)r0r`rar>r1r1r2test_children_recursive7s z#TestProcess.test_children_recursivec Cstjt}x@tjD]4}y||jd7<Wqtjk rFYqXqWt|jddddd}tj |}y|j dd}Wntj k rYnX|j t |t t|dS) NrXcSs|dS)NrXr1)rmr1r1r2Msz6TestProcess.test_children_duplicates..)keyrT)rGrY) collections defaultdictrr6rIrHErrorsorteditemsr7rPrSr8rr)r0tabler>r9cr1r1r2test_children_duplicatesDs   z$TestProcess.test_children_duplicatescCsdt}tj|j}|jx*tdD]}|jtjkr8Ptj dq$W|j |j |jtjdS)Nrfg{Gz?) rr6r7r9suspendrhrZSTATUS_STOPPEDrdr6resumerJ)r0r?r>rmr1r1r2test_suspend_resumeVs zTestProcess.test_suspend_resumecCs$|jttjd|jttjddS)Nr*rXrY)r<rr6r7rU)r0r1r1r2test_invalid_pidaszTestProcess.test_invalid_pidc;Cstj}|jddgd}|jt|jddgtjttj}|jdgdd}t|dt sp|j|ddt j ddtj d "|j|jd gd dd d iWdQRXt j ddtj |jdd |jtj |jd gdWdQRXt j ddtj|jdd "|j|jd gddd diWdQRXt j ddtd F|j}|jd t |j|jt|jd gdWdQRXWdQRX|jt|jdWdQRX|jt|jdgWdQRX|jt|jdd gWdQRXdS) Nrr\)attrsZ connectionsr)raZad_valuezpsutil.Process.niceT)ZcreaterMrrXZbar)r6r7as_dictr8rXkeysrrT isinstancer$rrOrSrRr9r< ZombieProcessNotImplementedErrorr>rrU)r0r>dr1r1r2 test_as_dictes> ""  "   zTestProcess.test_as_dictcCstjd@}tj}|j|j|jWdQRX|j|jdWdQRXtjd}|j|jWdQRX|j|jddS)Nz$psutil._psplatform.Process.cpu_timesrXrc)rrOr6r7oneshotrsr8 call_count)r0rqr>r1r1r2 test_oneshots   zTestProcess.test_oneshotc&Cstjd}tjdr}tj}|j:|j|j|j|j|jWdQRXWdQRX|j|jd|j|jdWdQRXWdQRXtjd}|j|jWdQRX|j|jddS)Nz$psutil._psplatform.Process.cpu_timesz(psutil._psplatform.Process.oneshot_enterrXrc)rrOr6r7rirsr8rj)r0m1m2r>rqr1r1r2test_oneshot_twices    " zTestProcess.test_oneshot_twicec Cst}tj|j}|j|jtr8ttjd|j|j |j ddddddg}t rjt rj|j dxTt|D]F}|jd sv||krqvyt||}|d krtr|d }n |tj}np|d kr|}|d }nX|dkr|tj}|tjd}n8|dkr|}|dg}n|dkr(|tj}n|}Wnztjk rV|jd|Yqvtjk rlYqvtjk rtr|dkrnYqvtk rYqvX|jd||fqvWdS)Nz %s not in retr9rZrBrriZmemory_info_exr_rrXrrcrWr#rrNz/ZombieProcess for %r was not supposed to happenrrz4NoSuchProcess exception not raised for %r, retval=%s)rWrW)rr)rr6r7r9rIrBr rrTrCrZrrr.rrr{rrrrErJrerrRrSrrf)r0r?r>Zexcluded_namesr\methrr1r1r2test_halfway_terminated_processs^               z+TestProcess.test_halfway_terminated_processcCsdd}t}|jtddtj|}|j|jtj|j|j |j ||j }|dk rl|j|gt |dr||j tj||j tjd||jt |dry||jdgWn:tk r}ztrtrd t|krnWYdd}~XnX||jdt |d r0tr$||jd dn ||jdt |drL||j tjd||j ||j||j||j|jtj|t rtr|j|tj|j|d d tjDit_|j|dd tjDdS)Nc _s,y |||Stjtjfk r&YnXdS)N)r6rerS)Zfunargskwargsr1r1r2succeed_or_zombie_p_excs z@TestProcess.test_zombie_process..succeed_or_zombie_p_excT)rGrrWr#rz not eligiblerrccSsg|] }|jqSr1)r9)rrmr1r1r2r9sz3TestProcess.test_zombie_process..cSsg|] }|jqSr1)r9)rrmr1r1r2r;s)rWrW)rWrW) rrr!r6r7r8r STATUS_ZOMBIE assertTruerZrbr]rrrrMr#rUr+rr rrr^rIrArDrr[rTrIZ_pmap)r0rtZzpidZzprocrerrr1r1r2test_zombie_processsP                zTestProcess.test_zombie_processc CsBtj}tjdtjdd}|js*t|js4tWdQRXdS)Nzpsutil.Processr)rM)r6r7rrOrerZrpro)r0r>rqr1r1r2$test_zombie_process_is_running_w_exc=s  z0TestProcess.test_zombie_process_is_running_w_excc CsHtj}tjdtjdd"}|j|jtj|js:t WdQRXdS)Nz!psutil._psplatform.Process.statusr)rM) r6r7rrOrer8rrurorp)r0r>rqr1r1r2 test_zombie_process_status_w_excGs z,TestProcess.test_zombie_process_status_w_excc Cs:dtjkr"|jtjtjddStjd}xtjD]}|dkrBq4t||}y |}Wntjk rlYq4X|d kr|j|j dq4|dkrt r|j|j dqt r|j|j dq4|dkr4|s4t |q4Wt|d ry|jtjWntjk rYnX|jts6|jdtj|jtjddS) Nrr9rrrrootzNT AUTHORITY\SYSTEMr\r)rr)r6rTr<rRr7Z_as_dict_attrnamesr{rSr8rrrr rprrrrbrr[rvrD)r0r>r\rprr1r1r2 test_pid_0Qs<      zTestProcess.test_pid_0cCs@dd}d|_tj}||j}|tjj}|j||dS)NcSsb|jdd|jdd|jddtrL|jdd|jdd|jddtdd|jDS) NZPSUTIL_TESTINGZPLATHOMEZ__CF_USER_TEXT_ENCODINGZVERSIONER_PYTHON_PREFER_32_BITZVERSIONER_PYTHON_VERSIONcSs$g|]\}}|jd|jdfqS)z )rstrip)rkvr1r1r2rsz@TestProcess.test_environ..clean_dict..)poprdictrY)rgr1r1r2 clean_dictzs      z,TestProcess.test_environ..clean_dict)ZmaxDiffr6r7rr:copyr8)r0rr>Zd1Zd2r1r1r2 test_environxs   zTestProcess.test_environcCstjd}t}t||d|jt|t|gtjtjd}t j |j }t |j |j |j|j|jjd|j|jddd|j|j|jddS) Na #include #include char * const argv[] = {"cat", 0}; char * const envp[] = {"A=1", "X", "C=3", 0}; int main(void) { /* Close stderr on exec so parent can wait for the execve to * finish. */ if (fcntl(2, F_SETFD, FD_CLOEXEC) != 0) return 0; return execve("/bin/cat", argv, envp); } )Zc_code)rstderrr*3)ACr)textwrapdedentr)rrr$r subprocessPIPEr6r7r9r-rvrZr8rrr communicate returncode)r0r^rr?r>r1r1r2test_weird_environs      zTestProcess.test_weird_environN)d__name__ __module__ __qualname____doc__r3r4r@rHrKrVr_rbrernrrr}rr,ZskipIfrrrrr+rrr'rrrr rr.rrrrrrrrrrrrr"r&rrrrrrrrrrrrr rrrr rrrrrrr)r+r0rr r:r?rCrrrErLrNrOrQrRr\r_r`rhrkrnrqrxryrzr|rrrr1r1r1r2r/Ks   /     +  . "   )    ) *  %    . @I  ' r/c@sReZdZdZeedr&ejZejZ ddZ ddZ ddZ d d Z d d Zd S)LimitedUserTestCasezRepeat the previous tests by using a limited user. Executed only on UNIX and only if the user who run the test script is root. rcs\tj|f||xDddt|DD].}t||fdd}t||tj||q&WdS)NcSsg|]}|jdr|qS)Ztest)r)rrmr1r1r2rsz0LimitedUserTestCase.__init__..c s&y Wntjk r YnXdS)N)r6rS)r0)rpr1r2test_s z+LimitedUserTestCase.__init__..test_)r/__init__rr{setattrtypes MethodType)r0rrrsattrrr1)rpr2rs   zLimitedUserTestCase.__init__cCs*tttj|tjdtjddS)Ni)r$r)r/r3r:setegidseteuid)r0r1r1r2r3s  zLimitedUserTestCase.setUpcCs&tj|jtj|jtj|dS)N)r:r PROCESS_UIDr PROCESS_GIDr/r4)r0r1r1r2r4s  zLimitedUserTestCase.tearDownc Cs8ytjjdWntjk r(Yn X|jddS)NrXzexception not raisedrY)r6r7rrSr)r0r1r1r2rs zLimitedUserTestCase.test_nicecCsdS)Nr1)r0r1r1r2rxsz'LimitedUserTestCase.test_zombie_processN)rrrrrr:rrr rrr3r4rrxr1r1r1r2rs rc@s0eZdZdZddZddZddZdd Zd S) TestPopenzTests for psutil.Popen class.cCs tdS)N)r!)r0r1r1r2r4szTestPopen.tearDownc Csjtddg}tj|tjtjdB}|j|j|j|jt ||j t t |d|j WdQRXdS)Nz-czimport time; time.sleep(60);)rrr)r r6Popenrrr\rsrrvrr<r=r{rI)r0rprocr1r1r2 test_miscs   zTestPopen.test_miscc Csftjtdgtjtjtjd}|jWdQRX|jjss                                             q53 PK! DD)__pycache__/test_bsd.cpython-36.opt-1.pycnu[3 JZcE@sdZddlZddlZddlZddlZddlZddlmZddlmZddlmZddlm Z ddl m Z ddl m Z dd l m Z dd l mZdd l mZdd l mZdd l mZddl mZddl mZerejdZejdkredZqdZndZddZddZeje dGdddejZeje dGdddejZeje dGdddejZeje dGd d!d!ejZe d"kree!dS)#z$Tests specific to all BSD platforms.N)BSD)FREEBSD)NETBSD)OPENBSD)get_test_subprocess) HAS_BATTERY)MEMORY_TOLERANCE) reap_children)retry_before_failing)run_test_module_by_name)sh)unittest)which SC_PAGE_SIZEmuseFc Cshtd|}tr(||jddd}nts0trF||jddd}yt|Stk rb|SXdS)zmExpects a sysctl command with an argument and parse the result returning only the value of interest. zsysctl z: N=)r rfindrrint ValueError)cmdlineresultr /usr/lib64/python3.6/test_bsd.pysysctl+s rcCs@td}x&|jdD]}|j|rPqWtdt|jdS)z+Thin wrapper around 'muse' cmdline utility.r zline not foundr)r split startswithrr)Zfieldoutlinerrrr:s  zBSD onlyc@seZdZdZeddZeddZeje dddZ d d Z eje d  d d dZ eje d  d ddZddZdS)BSDSpecificTestCasez)Generic tests common to all BSD variants.cCstj|_dS)N)rpid)clsrrr setUpClassNszBSDSpecificTestCase.setUpClasscCs tdS)N)r )r#rrr tearDownClassRsz!BSDSpecificTestCase.tearDownClassz -o lstart doesn't work on NETBSDcCsPtd|j}|jddj}tj|jj}tjdtj |}|j ||dS)Nzps -o lstart -p %sZSTARTEDz%a %b %e %H:%M:%S %Y) r r"replacestrippsutilProcessZ create_timetimeZstrftimeZ localtime assertEqual)selfoutputZstart_psZ start_psutilrrrtest_process_create_timeVs  z,BSDSpecificTestCase.test_process_create_timecCsdd}xtjddD]}tj|j}||j\}}}}|j|j||j|j|t|j|d krz|j d|j|ft|j |d kr|j d|j |fqWdS) NcSstd|j}|jd}|jd|jd}|jdd\}}}}|dkrRd}t|d}t|d}t|d}||||fS)Nz df -k "%s"rrZnoner&i)r r(rpopr)pathrlinesr devtotalusedfreerrrdfbs      z*BSDSpecificTestCase.test_disks..dfF)all izpsutil=%s, df=%si(ii(i) r)Zdisk_partitionsZ disk_usageZ mountpointr,Zdevicer5absr7Zfailr6)r-r8partZusager4r5r6r7rrr test_disks_s  zBSDSpecificTestCase.test_disksrzsysctl cmd not availablecCs td}|jtjdd|dS)Nzhw.ncpuT)Zlogical)rr,r) cpu_count)r-systrrrtest_cpu_count_logicalzsz*BSDSpecificTestCase.test_cpu_count_logicalcCstd}|j|tjjdS)Nz hw.physmem)rr,r)virtual_memoryr5)r-numrrrtest_virtual_memory_totalsz-BSDSpecificTestCase.test_virtual_memory_totalcCsxztjjD]j\}}ytd|}Wntk r:YqX|j|jd|k|dd|kr|j|jtt j d|dqWdS)Nz ifconfig %sZRUNNING)msgmtuz mtu (\d+)r) r)Z net_if_statsitemsr RuntimeErrorr,ZisuprErrefindall)r-nameZstatsrrrrtest_net_if_statssz%BSDSpecificTestCase.test_net_if_statsN)__name__ __module__ __qualname____doc__ classmethodr$r%r skipIfrr/r=rr@rCrKrrrrr!Js   r!z FREEBSD onlyc@seZdZeddZeddZeddZddZd d Z d d Z ed dZ eddZ eddZ eddZeddZeddZeddZeddZeje dddZeje ded d!Zeje ded"d#Zeje ded$d%Zeje ded&d'Zeje ded(d)Zeje ded*d+Zd,d-Zd.d/Zd0d1Zd2d3Z d4d5Z!eje" d6d7d8Z#eje" d6d9d:Z$eje"d;dS)?FreeBSDSpecificTestCasecCstj|_dS)N)rr")r#rrrr$sz"FreeBSDSpecificTestCase.setUpClasscCs tdS)N)r )r#rrrr%sz%FreeBSDSpecificTestCase.tearDownClassc Cstd|j}tj|jjdd}|jddd}x||r|j}|j}|dd\}}}} } |j} |jd||f| j|jt | | j | j j ds6|j|d | j q6WdS) Nzprocstat -v %sF)Zgroupedrrz%s-%s[r:) r r"r)r*Z memory_mapsrr1r,ZaddrrZrssr2r) r-rmapsr3r fields_startstopZpermsresmaprrrtest_proc_memory_mapss z-FreeBSDSpecificTestCase.test_proc_memory_mapscCs<td|j}|jtj|jj|jddjddS)Nzprocstat -b %srr)r r"r,r)r*Zexer)r-rrrr test_proc_exesz%FreeBSDSpecificTestCase.test_proc_execCsLtd|j}|jdjtj|jjdj|jddjdddS)Nzprocstat -c %s rrr)r r"r,joinr)r*rr)r-rrrrtest_proc_cmdlinesz)FreeBSDSpecificTestCase.test_proc_cmdlinec Cstd|j}|jddjdd\}}}}}}tj|j}|j} |j} |j| jt ||j| j t ||j| j t ||j| jt ||j| j t ||j| j t |dS)Nzprocstat -s %srrr) r r"rr)r*uidsgidsr,realrZ effectiveZsaved) r-rZeuidZruidZsuidZegidZrgidZsgidprcrdrrrtest_proc_uids_gidss& z+FreeBSDSpecificTestCase.test_proc_uids_gidscCsg}td|j}tj|j}x|jdD]}|jj}d|krtt|jd}|jj }|j |||j dq*d|kr*t|jd }|jj }|j |||j dq*Wt |dkrtddS) Nzprocstat -r %srz voluntary contextrz involuntary contextrz)couldn't find lines match in procstat outr]r])r r"r)r*rlowerr(rZnum_ctx_switchesZ voluntaryr,appendZ involuntarylenrG)r-testedrrfr pstat_value psutil_valuerrrtest_proc_ctx_switchess"        z.FreeBSDSpecificTestCase.test_proc_ctx_switchescCsg}td|j}tj|j}x|jdD]}|jj}d|krtd|jd jdd }|jj }|j |||j dq*d|kr*td|jd jdd }|jj }|j |||j dq*Wt |dkrtd dS)Nzprocstat -r %srz user timez0.r.z system timerz)couldn't find lines match in procstat outr]r]r]r])r r"r)r*rrhr(floatZ cpu_timesuserr,risystemrjrG)r-rkrrfr rlrmrrrtest_proc_cpu_timess"        z+FreeBSDSpecificTestCase.test_proc_cpu_timescCs&tdt}|jtjj|tddS)Nzvm.stats.vm.v_active_count)delta)rPAGESIZEassertAlmostEqualr)rAactiver)r-r?rrrtest_vmem_actives z(FreeBSDSpecificTestCase.test_vmem_activecCs&tdt}|jtjj|tddS)Nzvm.stats.vm.v_inactive_count)rt)rrurvr)rAinactiver)r-r?rrrtest_vmem_inactives z*FreeBSDSpecificTestCase.test_vmem_inactivecCs&tdt}|jtjj|tddS)Nzvm.stats.vm.v_wire_count)rt)rrurvr)rAwiredr)r-r?rrrtest_vmem_wireds z'FreeBSDSpecificTestCase.test_vmem_wiredcCs&tdt}|jtjj|tddS)Nzvm.stats.vm.v_cache_count)rt)rrurvr)rAcachedr)r-r?rrrtest_vmem_cacheds z(FreeBSDSpecificTestCase.test_vmem_cachedcCs&tdt}|jtjj|tddS)Nzvm.stats.vm.v_free_count)rt)rrurvr)rAr7r)r-r?rrrtest_vmem_free s z&FreeBSDSpecificTestCase.test_vmem_freecCs"td}|jtjj|tddS)Nz vfs.bufspace)rt)rrvr)rAbuffersr)r-r?rrrtest_vmem_bufferssz)FreeBSDSpecificTestCase.test_vmem_bufferszmuse not installedcCstd}|jtjj|dS)NZTotal)rr,r)rAr5)r-rBrrrtest_muse_vmem_totalsz,FreeBSDSpecificTestCase.test_muse_vmem_totalcCs"td}|jtjj|tddS)NZActive)rt)rrvr)rArwr)r-rBrrrtest_muse_vmem_activesz-FreeBSDSpecificTestCase.test_muse_vmem_activecCs"td}|jtjj|tddS)NZInactive)rt)rrvr)rAryr)r-rBrrrtest_muse_vmem_inactive#sz/FreeBSDSpecificTestCase.test_muse_vmem_inactivecCs"td}|jtjj|tddS)NZWired)rt)rrvr)rAr{r)r-rBrrrtest_muse_vmem_wired*sz,FreeBSDSpecificTestCase.test_muse_vmem_wiredcCs"td}|jtjj|tddS)NZCache)rt)rrvr)rAr}r)r-rBrrrtest_muse_vmem_cached1sz-FreeBSDSpecificTestCase.test_muse_vmem_cachedcCs"td}|jtjj|tddS)NZFree)rt)rrvr)rAr7r)r-rBrrrtest_muse_vmem_free8sz+FreeBSDSpecificTestCase.test_muse_vmem_freecCs"td}|jtjj|tddS)NZBuffer)rt)rrvr)rArr)r-rBrrrtest_muse_vmem_buffers?sz.FreeBSDSpecificTestCase.test_muse_vmem_bufferscCs|jtjjtddddS)Nzvm.stats.sys.v_swtchi)rt)rvr) cpu_stats ctx_switchesr)r-rrrtest_cpu_stats_ctx_switchesFs z3FreeBSDSpecificTestCase.test_cpu_stats_ctx_switchescCs|jtjjtddddS)Nzvm.stats.sys.v_intri)rt)rvr)r interruptsr)r-rrrtest_cpu_stats_interruptsJs z1FreeBSDSpecificTestCase.test_cpu_stats_interruptscCs|jtjjtddddS)Nzvm.stats.sys.v_softi)rt)rvr)rZsoft_interruptsr)r-rrrtest_cpu_stats_soft_interruptsNs z6FreeBSDSpecificTestCase.test_cpu_stats_soft_interruptscCs|jtjjtddddS)Nzvm.stats.sys.v_syscalli)rt)rvr)rZsyscallsr)r-rrrtest_cpu_stats_syscallsRs z/FreeBSDSpecificTestCase.test_cpu_stats_syscallscCsLtd}||jddd}|d|jd}t|}|j|tjdS)Nzsysctl kern.boottimez sec = ,)rrrr,r) boot_time)r-sZbtimerrrtest_boot_time\s z&FreeBSDSpecificTestCase.test_boot_timez no batterycCsdd}td}tdd|jdD}tj}t|djdd }|d }|j|j||d krt|j|j tj n|j||j |dS) NcSs(t|d\}}t|d\}}d||fS)N<z%d:%02d)divmod)Zsecsmrhrrr secs2hoursgsz@FreeBSDSpecificTestCase.test_sensors_battery..secs2hoursz acpiconf -i 0cSs(g|] }|jdd|jddfqS) rrr])r).0xrrr msz@FreeBSDSpecificTestCase.test_sensors_battery..rzRemaining capacity:%r&zRemaining time:unknown) r dictrr)sensors_batteryrr'r,percentsecsleftZPOWER_TIME_UNLIMITED)r-rrrVZmetricsrZremaining_timerrrtest_sensors_batteryesz,FreeBSDSpecificTestCase.test_sensors_batterycCsl|jtjjtd|jtjjtddktjj}|dkrT|jtddn|j|tdddS)Nzhw.acpi.battery.lifezhw.acpi.aclinerrzhw.acpi.battery.timerr])r,r)rrrZ power_pluggedr)r-rrrr#test_sensors_battery_against_sysctlxs    z;FreeBSDSpecificTestCase.test_sensors_battery_against_sysctlz has batteryc Cs@|jttdtdtdWdQRX|jtjdS)Nzhw.acpi.battery.lifezhw.acpi.battery.timezhw.acpi.acline)Z assertRaisesrGrZ assertIsNoner)r)r-rrrtest_sensors_battery_no_batterys  z7FreeBSDSpecificTestCase.test_sensors_battery_no_batteryN)&rLrMrNrPr$r%r r\r^rargrnrsrxrzr|r~rrr rQMUSE_AVAILABLErrrrrrrrrrrrrrrrrrrrrRsF            rRz OPENBSD onlyc@seZdZddZdS)OpenBSDSpecificTestCasecCs6td}tjj|d}tjjtj}|j||dS)Nz kern.boottimez%a %b %d %H:%M:%S %Y)rdatetimeZstrptimeZ fromtimestampr)rr,)r-rZsys_btZ psutil_btrrrrsz&OpenBSDSpecificTestCase.test_boot_timeN)rLrMrNrrrrrrsrz NETBSD onlyc@s`eZdZeddZddZddZddZd d Zd d Z d dZ ddZ ddZ ddZ dS)NetBSDSpecificTestCasec CsRtdd2}x*|D]"}|j|rt|jddSqWWdQRXtd|dS)Nz /proc/meminforbriz can't find %s)openrrrr)Zlook_forfr rrr parse_meminfos    "z$NetBSDSpecificTestCase.parse_meminfocCs|jtjj|jddS)Nz MemTotal:)r,r)rAr5r)r-rrrtest_vmem_totalsz&NetBSDSpecificTestCase.test_vmem_totalcCs |jtjj|jdtddS)NzMemFree:)rt)rvr)rAr7rr)r-rrrrsz%NetBSDSpecificTestCase.test_vmem_freecCs |jtjj|jdtddS)NzBuffers:)rt)rvr)rArrr)r-rrrrsz(NetBSDSpecificTestCase.test_vmem_bufferscCs |jtjj|jdtddS)Nz MemShared:)rt)rvr)rAZsharedrr)r-rrrtest_vmem_sharedsz'NetBSDSpecificTestCase.test_vmem_sharedcCs |jtjj|jdtddS)Nz SwapTotal:)rt)rvr) swap_memoryr5rr)r-rrrtest_swapmem_totalsz)NetBSDSpecificTestCase.test_swapmem_totalcCs |jtjj|jdtddS)Nz SwapFree:)rt)rvr)rr7rr)r-rrrtest_swapmem_freesz(NetBSDSpecificTestCase.test_swapmem_freecCs"tj}|j|j|j|jdS)N)r)rr,r6r5r7)r-Zsmemrrrtest_swapmem_usedsz(NetBSDSpecificTestCase.test_swapmem_usedc Csbtdd8}x0|D] }|jdrt|jd}PqWtdWdQRX|jtjj|dddS)Nz /proc/statrsintrrzcouldn't find linei)rt) rrrrrrvr)rr)r-rr rrrrrs   z0NetBSDSpecificTestCase.test_cpu_stats_interruptsc Csbtdd8}x0|D] }|jdrt|jd}PqWtdWdQRX|jtjj|dddS)Nz /proc/statrsctxtrzcouldn't find linei)rt) rrrrrrvr)rr)r-rr rrrrrs   z2NetBSDSpecificTestCase.test_cpu_stats_ctx_switchesN)rLrMrN staticmethodrrrrrrrrrrrrrrrs  r__main__)"rOrosrHr+r)rrrrZ psutil.testsrrrr r r r r rsysconfrugetuidrrrrQZTestCaser!rRrrrL__file__rrrr sL                 K   B PK!p\}c3c3+__pycache__/test_posix.cpython-36.opt-1.pycnu[3 JZ?@sdZddlZddlZddlZddlZddlZddlZddlZddlZddlm Z ddlm Z ddlm Z ddlm Z ddlm Z ddlmZdd lmZdd lmZdd lmZdd lmZdd lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddZ"ddZ#ddZ$ej%e d Gd!d"d"ej&Z'ej%e d Gd#d$d$ej&Z(e)d%kree*dS)&zPOSIX specific tests.N)AIX)BSD)LINUX)OPENBSD)OSX)POSIX)SUNOS)callable)PY3)APPVEYOR)get_kernel_version)get_test_subprocess)mock) PYTHON_EXE) reap_children)retry_before_failing)run_test_module_by_name)sh)skip_on_access_denied)TRAVIS)unittest) wait_for_pid)whichc Cspts|jdd}tr |jdd}tr0|jdd}t|}tsN|jddj}yt|Stk rj|SXd S) zkExpects a ps command with a -o argument and parse the result returning only the value of interest. z --no-headers  z-o startz-o stimez-o rssz -o rssize N) rreplacerrrsplitstripint ValueError)cmdoutputr#"/usr/lib64/python3.6/test_posix.pyps+s   r%cCs&d}tr d}td||fjddS)NcommandZcommzps --no-headers -o %s -p %srr)rr%r)pidfieldr#r#r$ps_nameIsr)cCs d}ts trd}td||fS)Nr&argszps --no-headers -o %s -p %s)rrr%)r'r(r#r#r$ps_argsPsr+z POSIX onlyc@seZdZdZeddZeddZddZdd Zd d Z d d Z ddZ e e ddZe e ddZddZddZddZddZejepedddZdd Zd!d"Zejed#ejed$d%d&Zd'd(Zd)S)* TestProcesszBCompare psutil results against 'ps' command line utility (mainly).cCs&ttddgtjdj|_t|jdS)Nz-Ez-O)stdin)r r subprocessPIPEr'r)clsr#r#r$ setUpClass[s zTestProcess.setUpClasscCs tdS)N)r)r0r#r#r$ tearDownClassaszTestProcess.tearDownClasscCs.td|j}tj|jj}|j||dS)Nzps --no-headers -o ppid -p %s)r%r'psutilProcessZppid assertEqual)selfZppid_psZ ppid_psutilr#r#r$ test_ppideszTestProcess.test_ppidcCs0td|j}tj|jjj}|j||dS)Nzps --no-headers -o uid -p %s)r%r'r3r4uidsrealr5)r6Zuid_psZ uid_psutilr#r#r$test_uidjszTestProcess.test_uidcCs0td|j}tj|jjj}|j||dS)Nzps --no-headers -o rgid -p %s)r%r'r3r4Zgidsr9r5)r6Zgid_psZ gid_psutilr#r#r$test_gidoszTestProcess.test_gidcCs.td|j}tj|jj}|j||dS)Nzps --no-headers -o user -p %s)r%r'r3r4usernamer5)r6Z username_psZusername_psutilr#r#r$ test_usernametszTestProcess.test_usernamec Cs@tj}tjdtd }|j|jt|jj WdQRXdS)Nzpsutil.pwd.getpwuid) side_effect) r3r4rpatchKeyErrorr5r<strr8r9)r6pZfunr#r#r$test_username_no_resolutionysz'TestProcess.test_username_no_resolutioncCs@tjdtd|j}tj|jjdd}|j||dS)Ng?zps --no-headers -o rss -p %sri)timesleepr%r'r3r4 memory_infor5)r6Zrss_psZ rss_psutilr#r#r$test_rss_memorys zTestProcess.test_rss_memorycCs@tjdtd|j}tj|jjdd}|j||dS)Ng?zps --no-headers -o vsz -p %sri)rDrEr%r'r3r4rFr5)r6Zvsz_psZ vsz_psutilr#r#r$test_vsz_memorys zTestProcess.test_vsz_memorycCsZt|j}tjj|j}tj|jjj}t j dd|}t j dd|}|j ||dS)Nz\d.\d) r)r'ospathbasenamelowerr3r4nameresubr5)r6Zname_psZ name_psutilr#r#r$ test_names  zTestProcess.test_namecCs^d}dddg}tjd|d8tjd|dtj}|j|jdWdQRXWdQRXdS)Nzlong-program-namezlong-program-name-extendedZfooZbarzpsutil._psplatform.Process.name) return_valuez"psutil._psplatform.Process.cmdline)rr?r3r4r5rN)r6rNcmdlinerBr#r#r$test_name_longs   zTestProcess.test_name_longcCs\d}tjd|d@tjdtjdddtj}|j|jdWdQRXWdQRXdS)Nzlong-program-namezpsutil._psplatform.Process.name)rRz"psutil._psplatform.Process.cmdlinerrI)r>)rr?r3 AccessDeniedr4r5rN)r6rNrBr#r#r$test_name_long_cmdline_ad_excs z)TestProcess.test_name_long_cmdline_ad_exccCs\d}tjd|d@tjdtjdddtj}|jtj|jWdQRXWdQRXdS)Nzlong-program-namezpsutil._psplatform.Process.name)rRz"psutil._psplatform.Process.cmdlinerrI)r>)rr?r3Z NoSuchProcessr4 assertRaisesrN)r6rNrBr#r#r$test_name_long_cmdline_nsp_excs z*TestProcess.test_name_long_cmdline_nsp_exczps -o start not availablecCshtd|jjdd}tj|jj}tjj|jd}t |}tjj|jd}|j |||gdS)Nzps --no-headers -o start -p %srrz%H:%M:%S) r%r'rr3r4Z create_timedatetimeZ fromtimestampZstrftimeroundassertIn)r6Ztime_psZ time_psutilZtime_psutil_tstampZround_time_psutilZround_time_psutil_tstampr#r#r$test_create_times  zTestProcess.test_create_timec Cs`t|j}tj|jj}y|j||Wn0tk rZ|dt|}|j||YnXdS)N)r)r'r3r4Zexer5AssertionErrorlen)r6Z ps_pathnameZpsutil_pathnameZadjusted_ps_pathnamer#r#r$test_exes zTestProcess.test_execCs0t|j}djtj|jj}|j||dS)Nr)r+r'joinr3r4rSr5)r6Z ps_cmdlineZpsutil_cmdliner#r#r$ test_cmdlines zTestProcess.test_cmdlineznot reliable on SUNOSznot reliable on AIXcCs*td|j}tjj}|j||dS)Nzps --no-headers -o nice -p %s)r%r'r3r4nicer5)r6Zps_niceZ psutil_nicer#r#r$ test_nices zTestProcess.test_nicec sfdd}tjtj}g}ddddddd d d d g }trNtdkrN|jdtrftdkrf|jdxttjD]jdsr|krqrqry0|j }xt d D]}||qW|j }Wntj k rYqrXt ||dkrrd||f}|j|qrW|r|j ddj|dS)NcsBf}t|d}|dk r:t|r:dkr0tjf}||n|dS)Nrlimit)getattrr r3Z RLIMIT_NOFILE)rBattrr*)rNr#r$calls  z&TestProcess.test_num_fds..callZ terminatekillZsuspendZresumerbZ send_signalwaitZchildrenZas_dictZmemory_info_ex$rdZnum_ctx_switches_rz@failure while processing Process.%s method (before=%s, after=%s)r)rjrkrl)rjrkrm)r3r4rJgetpidrr appenddir startswithZnum_fdsrangerUabsfailr`) r6rgrBZfailuresZ ignored_namesZnum1xZnum2rur#)rNr$ test_num_fdss4      zTestProcess.test_num_fdsN)__name__ __module__ __qualname____doc__ classmethodr1r2r7r:r;r=rCrrrGrHrQrTrVrXrskipIfrrr\r_rarrrcrwr#r#r#r$r,Ws,           r,c@seZdZdZeddZejedeje deje d ddd Z eje p`e o`e j d ed d Zd dZddZddZddZejedddZdS)TestSystemAPIszTest some system APIs.cCststrddddg}n ddddg}t|tjd}|jdj}trRt|t j j }g}x<|j dd dD]&}|rjt |j dj}|j|qjW|j|jtj}|j|jtstrd|kr|jdd|j||dS) Nr%z-Az-or'Zax)stdoutrrr)rrr r.r/Z communicaterr rAsysrencodingrrrpremover'r3Zpidssortrrinsertr5)r6r!rBr"Zpids_psliner'Z pids_psutilr#r#r$ test_pids s&   zTestSystemAPIs.test_pidszunreliable on SUNOSzunreliable on TRAVISZifconfigzno ifconfig cmdcCsVtd}xHtjddjD]4}x.|jD]}|j|r(Pq(W|jd||fqWdS)Nz ifconfig -aT)Zpernicz/couldn't find %s nic in 'ifconfig -a' output %s)rr3Znet_io_counterskeysrrrru)r6r"Znicrr#r#r$test_nic_names?s zTestSystemAPIs.test_nic_namesz unreliable on APPVEYOR or TRAVIScCsxtd}|jd}dd|D}dd|D}|jt|ttjx,tjD] }|j|j||j|j|qPWdS)NZwhorcSsg|]}|jdqS)r)r).0rvr#r#r$ Tsz-TestSystemAPIs.test_users..cSsg|]}|jdqS)r)r)rrvr#r#r$rUs) rrr5r^r3usersr[rNZterminal)r6outlinesrZ terminalsur#r#r$ test_usersNs zTestSystemAPIs.test_usersc Cs<tjdttjdd}|jttjjt j WdQRXdS)Nzpsutil._psposix.os.killrI)r>) rr?OSErrorerrnoEBADFrWr3_psposixZ pid_existsrJro)r6mr#r#r$test_pid_exists_let_raise[sz(TestSystemAPIs.test_pid_exists_let_raisec Cs<tjdttjdd}|jttjjt j WdQRXdS)Nzpsutil._psposix.os.waitpidrI)r>) rr?rrrrWr3rwait_pidrJro)r6rr#r#r$test_os_waitpid_let_raisedsz(TestSystemAPIs.test_os_waitpid_let_raisec CsDtjdttjdd$}|jtjjtjj t j ddWdQRXdS)Nzpsutil._psposix.os.waitpidrI)r>g{Gz?)Ztimeout) rr?rrZEINTRrWr3rZTimeoutExpiredrrJro)r6rr#r#r$test_os_waitpid_eintrls z$TestSystemAPIs.test_os_waitpid_eintrc Cs4tjddd}|jttjjtjWdQRXdS)Nzpsutil._psposix.os.waitpidr)rR)rr) rr?rWr r3rrrJro)r6rr#r#r$test_os_waitpid_bad_ret_statusus  z-TestSystemAPIs.test_os_waitpid_bad_ret_statuszunreliable on AIXc Csdd}d }xtjddD]}tj|j}y||j\}}}}WnLtk r} z0t| j} d| ksvd| ksvd | krzwnWYdd} ~ XqX|j|j ||d |j|j ||d |j|j ||d |j|j |d d qWdS)NcSsvtd|j}|jdd}|j}t|dd}t|dd}t|dd}t|djdd }||||fS) Nzdf -k %srrirj%rI)rrrrfloatr)devicerrZfieldstotalusedfreepercentr#r#r$dfsz*TestSystemAPIs.test_disk_usage..dfriF)allzno such file or directoryzraw devices not supportedzpermission denied)Zdeltarii@) r3Zdisk_partitionsZ disk_usageZ mountpointr RuntimeErrorrArMZassertAlmostEqualrrrr) r6rZ tolerancepartZusagerrrrerrr#r#r$test_disk_usage~s"   zTestSystemAPIs.test_disk_usageN)rxryrzr{rrrr}rrrrr r3rrrrrrrrr#r#r#r$r~s       r~__main__)+r{rYrrJrOr.rrDr3rrrrrrrZpsutil._compatr r Z psutil.testsr r r rrrrrrrrrrrr%r)r+r}ZTestCaser,r~rx__file__r#r#r#r$sT                        E  PK!Nh$__pycache__/test_misc.cpython-36.pycnu[3 JZ@s|dZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl m Z ddl m Z ddl m Z ddlmZddlmZddlmZdd lmZdd lmZdd lmZdd lmZdd lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddlm$Z$ddlm%Z%ddlm&Z&ddlm'Z'ddlm(Z(ddlm)Z)ddlm*Z*dd lm+Z+dd!lm,Z,dd"lm-Z-dd#lm.Z.dd$lm/Z/dd%lm0Z0dd&lm1Z1dd'lm2Z2dd(lm3Z3dd)lm4Z4dd*lm5Z5dd+lm6Z6dd,lm7Z7dd-lm8Z8dd.lm9Z9dd/lm:Z:dd0lm;Z;dd1lmej?d4d5Z@Gd6d7d7e8j=ZAe8jBe6d8e8jBe7oejCjDe2 d9Gd:d;d;e8j=ZEGdd?d?e8j=ZGGd@dAdAe8j=ZHGdBdCdCe8j=ZIGdDdEdEe8j=ZJGdFdGdGe8j=ZKeLdHkrxe0eMdS)Iz Miscellaneous tests. N)LINUX)POSIX)WINDOWS)memoize)memoize_when_activated) supports_ipv6) wrap_numbers)PY3)APPVEYOR) bind_socket)bind_unix_socket) call_until)chdir)create_proc_children_pair)create_sockets)create_zombie_proc)DEVNULL) get_free_port)get_test_subprocess) HAS_BATTERY)HAS_CONNECTIONS_UNIX)HAS_MEMORY_FULL_INFO)HAS_MEMORY_MAPS)HAS_SENSORS_BATTERY)HAS_SENSORS_FANS)HAS_SENSORS_TEMPERATURES)import_module_by_path) is_namedtuple)mock) PYTHON_EXE) reap_children) reload_module)retry)ROOT_DIR)run_test_module_by_name) safe_rmpath) SCRIPTS_DIR)sh)tcp_socketpair)TESTFN)TOX)TRAVIS)unittest)unix_socket_path)unix_socketpair) wait_for_file) wait_for_pidc@seZdZefddZddZefddZefddZefd d Zefd d Z d dZ ddZ ddZ ddZ ddZddZddZddZddZdd Zd!d"Zd#d$Zd%d&Zd'd(Zd)S)*TestMisccCsntj}||}|jd||jd|j||jd||j|j|tjjtjdtjt j d@tj}||}|jd|j||jd||j d|WdQRXtjjtjdtj t j d@tj}||}|jd|j||jd||j d|WdQRXtjjtjdtj t j d4tj}||}|jd|j||j d|WdQRXdS)Nzpsutil.Processzpid=%szname=name) side_effectZzombieZ terminated)psutilProcessassertInpidr2rpatchobject ZombieProcessosgetpid assertNotIn NoSuchProcess AccessDenied)selffuncprrD!/usr/lib64/python3.6/test_misc.pytest_process__repr__Os4       zTestMisc.test_process__repr__cCs|jtddS)N)rA)rFstr)r@rDrDrEtest_process__str__kszTestMisc.test_process__str__cCsN|jttjdd|jttjdddd|jttjdddddS)NiAz7psutil.NoSuchProcess process no longer exists (pid=321)foo)r2zCpsutil.NoSuchProcess process no longer exists (pid=321, name='foo'))msgzpsutil.NoSuchProcess foo) assertEqualreprr4r>)r@rArDrDrEtest_no_such_process__repr__ns z%TestMisc.test_no_such_process__repr__cCsj|jttjdd|jttjdddd|jttjddddd|jttjddd d dS) NiAzEpsutil.ZombieProcess process still exists but it's a zombie (pid=321)rI)r2zQpsutil.ZombieProcess process still exists but it's a zombie (pid=321, name='foo'))r2ppidzYpsutil.ZombieProcess process still exists but it's a zombie (pid=321, name='foo', ppid=1))rJzpsutil.ZombieProcess foo)rKrLr4r:)r@rArDrDrEtest_zombie_process__repr__zs z$TestMisc.test_zombie_process__repr__cCsN|jttjdd|jttjdddd|jttjdddddS)NiAzpsutil.AccessDenied (pid=321)rI)r2z)psutil.AccessDenied (pid=321, name='foo'))rJzpsutil.AccessDenied foo)rKrLr4r?)r@rArDrDrEtest_access_denied__repr__s z#TestMisc.test_access_denied__repr__cCsP|jttjdd|jttjdddd|jttjddddddS) NiAz/psutil.TimeoutExpired timeout after 321 secondso)r7z9psutil.TimeoutExpired timeout after 321 seconds (pid=111)rI)r7r2zEpsutil.TimeoutExpired timeout after 321 seconds (pid=111, name='foo'))rKrLr4ZTimeoutExpired)r@rArDrDrEtest_timeout_expired__repr__s z%TestMisc.test_timeout_expired__repr__cCs>tj}tj}|j||d|_|j|||j|ddS)NrrI)rr)r4r5rKZ_identassertNotEqual)r@p1p2rDrDrEtest_process__eq__s   zTestMisc.test_process__eq__cCs(ttjtjg}|jt|ddS)NrN)setr4r5rKlen)r@srDrDrEtest_process__hash__szTestMisc.test_process__hash__c Cstt}x|D]~}|d krq|jd sy t|Wqtk r|tjkrtt|}|dkr`w|jdk rd |jjkr|j d |YqXqWxtjD]}|j ||qWdS)Ncallableerror namedtupletestslongtestNUM_CPUS BOOT_TIME TOTAL_PHYMEM_Z deprecatedz%r not in psutil.__all__) r\r]r^r_r`rarbrcrd) dirr4 startswith __import__ ImportError__all__getattr__doc__lowerfailr6)r@Z dir_psutilr2ZfunrDrDrE test__all__s&       zTestMisc.test__all__cCs$|jdjddtjDtjdS)N.cSsg|] }t|qSrD)rG).0xrDrDrE sz)TestMisc.test_version..)rKjoinr4 version_info __version__)r@rDrDrE test_versionszTestMisc.test_versioncCs"tj}d|_|jd|jdS)N1rI)r4r5rIr=as_dict)r@rBrDrDrE!test_process_as_dict_no_new_namessz*TestMisc.test_process_as_dict_no_new_namescstfdd}gx:tdD].}|}fif}|j|||jtdqWx.foorN)barrz foo docstring)rN)rN)rrangerKrY cache_clearrl)r@rIrrretZexpectedrD)r~rE test_memoizes.      zTestMisc.test_memoizecsGfddd}|}g|j|j|jtdg|jj|j|j|jtdg|jj|j|j|jtddS)NcseZdZefddZdS)z1TestMisc.test_memoize_when_activated..FoocsjddS)N)r{)r@)r~rDrErIsz5TestMisc.test_memoize_when_activated..Foo.fooN)__name__ __module__ __qualname__rrIrD)r~rDrEFoosrrrN)rIrKrYZcache_activateZcache_deactivate)r@rfrD)r~rEtest_memoize_when_activateds   z$TestMisc.test_memoize_when_activatedcCsddlm}dd}|j|d|ddi|j|d|dd|d d i|j|d |dd|d d i|j|d |dd|d d i|j|d|ddi|j|d|ddi|j|d|ddidS)Nr)parse_environ_blockcSstr |jS|S)N)rupper)rZrDrDrEksz,TestMisc.test_parse_environ_block..kza=1arxz a=1b=2b2za=1b=z a=1b=2c=3zxxxa=1z a=1=b=2za=1b=2)psutil._commonrrK)r@rrrDrDrEtest_parse_environ_blocks     z!TestMisc.test_parse_environ_blockcCs8|jtjtrtjd }d|_tjt s:tWdQRXtjtjdtjd}t sjt|j sttWdQRXtjtjdtj d$}t sttj|j stWdQRXtjtjdtj d$}t sttj|j stWdQRXn0|j t  tjtj tj}|jdWdQRXdS) Nzpsutil._common.socketFzpsutil._common.socket.socket)r3z!psutil._common.socket.socket.bind::1r)rr) addCleanuprrrr8Zhas_ipv6AssertionErrorsocketr]calledZgaierror assertRaises ExceptionAF_INET6 SOCK_STREAMZbind)r@rZsockrDrDrEtest_supports_ipv6%s4         zTestMisc.test_supports_ipv6cCsddlm}tjjt}||s$t|tjj| s:ttj dt t j dd|j t ||WdQRXtj dt t jdd|j t ||WdQRXtj dt t jdd|| stWdQRXtj ddd|| stWdQRXdS) Nr) isfile_strictzpsutil._common.os.statrI)r3zpsutil._common.stat.S_ISREGF) return_value)rrr;pathabspath__file__rdirnamerr8OSErrorerrnoZEPERMrZEACCESEINVAL)r@rZ this_filerDrDrEtest_isfile_strictEs   zTestMisc.test_isfile_strictcsfdd}|tjj|tj|tj|tj|tjdd|tjtrpt j j d rpnt s|tj |tj|tjt j|tjdS)Ncs<tdk rtjtj|tj|}tj|}j||dS)N)jsonloadsdumpspicklerK)rrr)r@rDrEcheckWs   z*TestMisc.test_serialization..checkr)intervalz/proc/diskstats)r4r5ryZvirtual_memoryZ swap_memoryZ cpu_timesZcpu_times_percentnet_io_countersrr;rexistsr disk_io_countersZdisk_partitionsZ disk_usagegetcwdusers)r@rrD)r@rEtest_serializationVs       zTestMisc.test_serializationcCsVtjjtd}tr*tjj| r*|jdSt|}|jt |j |j |j t jdS)Nzsetup.pyzcan't find setup.py)r;rrtr#r+rZskipTestrr SystemExitZsetuprKZ get_versionr4rv)r@Zsetup_pymodulerDrDrEtest_setup_scriptms  zTestMisc.test_setup_scriptcCstjjtjdtjd}tj|js*tWdQRXtjjtjdtjdd}tj|jsbtWdQRXtjjtjdt d.}|j t tjWdQRX|jstWdQRXdS)NZ create_time)r3rN) rr8r9r4r5r?rrr: ValueErrorr)r@methrDrDrEtest_ad_on_process_creationus      z$TestMisc.test_ad_on_process_creationcCsRtjddd:|jt}ttWdQRX|jdt|jj WdQRXdS)Nzpsutil._psplatform.cext.versionz0.0.0)rzversion conflict) rr8rrir!r4r6rG exceptionrm)r@cmrDrDrEtest_sanity_version_checks   z"TestMisc.test_sanity_version_checkN)rrrrLrFrHrMrPrQrSrWr[rorwrzrrrrrrrrrrDrDrDrEr1Ms(   # r1rIza b cc@seZdZddZeZddZddZddZd d Zd d Z d dZ ddZ ddZ ddZ ddZddZddZejej pej dddZdS)TestWrapNumberscCs tjdS)N)rr)r@rDrDrEsetUpszTestWrapNumbers.setUpcCs&dtdddi}|jt|d|dS)Ndisk1disk_io)ntrKr)r@inputrDrDrEtest_first_callszTestWrapNumbers.test_first_callcCs8dtdddi}|jt|d||jt|d|dS)Nrrr)rrKr)r@rrDrDrEtest_input_hasnt_changedsz(TestWrapNumbers.test_input_hasnt_changedcCsdtdddi}|jt|d|dtdddi}|jt|d|dtdddi}|jt|d|dtdddi}|jt|d|dS) Nrrr )rrKr)r@rrDrDrEtest_increase_but_no_wrapsz)TestWrapNumbers.test_increase_but_no_wrapcCsdtdddi}|jt|d|dtdddi}|jt|ddtdddidtdddi}|jt|ddtdddidtdddi}|jt|ddtdddidtdddi}|jt|ddtddd idtdddi}|jt|ddtddd idtd ddi}|jt|ddtd dd idtd ddi}|jt|ddtddd idtd ddi}|jt|ddtddd idS) NrdrrnZr2()rrKr)r@rrDrDrE test_wraps4        zTestWrapNumbers.test_wrapcCstdtdddi}|jt|d|tdddtdddd}|jt|d|dtdddi}|jt|d|dS)Nrrr)rdisk2)rrKr)r@rrDrDrEtest_changing_keyss z"TestWrapNumbers.test_changing_keyscCs.tdddtdddd}|jt|d|tdddtdddd}|jt|dtdddtdddddtdddi}|jt|d|tdddtdddd}|jt|d|tdddtdddd}|jt|d|tdddtdddd}|jt|dtdddtdddddS)Nrr)rrrrrr)rrKr)r@rrDrDrEtest_changing_keys_w_wraps*         z)TestWrapNumbers.test_changing_keys_w_wrapc Csbd'd(d)d*d"}|jt|d#||jt|d#|d+d,d-d.d"}t|d#}|j|d%dd&dS)/N,#RȷrtUrr6$NrrU "r4\)nvme0n1Z nvme0n1p1Z nvme0n1p2Z nvme0n1p3rrri) rrrrrrrrr) rrrrrrrrr) rrrrrrrrr) rrrrrrrrr) rrrrrrrrr) rrrrrrrrr) rrrrrrrrr) rrrrrrrrr)rKr)r@doutrDrDrEtest_real_datas zTestWrapNumbers.test_real_datacCsbdtdddi}t|dtj}|j|dd|i|j|ddii|j|ddiidS)NrrrrrNr)rr cache_inforK)r@rcacherDrDrEtest_cache_first_calls  z%TestWrapNumbers.test_cache_first_callc Csdtdddi}t|ddtdddi}t|dtj}|j|dd|i|j|ddddd dd dii|j|ddiidS) NrrrrrrNr)rr)rrN)rr)rrrrK)r@rrrDrDrEtest_cache_call_twices  z%TestWrapNumbers.test_cache_call_twicec sdtdddi}t|ddtdddi}t|dtj}j|dd|ij|ddd dddddiij|dddtdgiifdd }dtdddi}t|dtj}j|dd|i|dtddd i}t|dtj}j|dd|i|dtddd i}t|dtj}j|dd|ij|dddddddd iij|dddtdgiidS)NrrrrrrNrc sJtj}j|ddddddd diij|dddtd giidS) NrNrrrrr)rr)rrN)rr)rr)rrrKrX)r)r@rDrEassert_4s   z0TestWrapNumbers.test_cache_wrap..assert_rrr)rr)rrN)rr)rr)rr)rrN)rr)rr)rrrrKrX)r@rrrrD)r@rEtest_cache_wrap%s:      zTestWrapNumbers.test_cache_wrapc Csdtdddi}t|dtdddtdddd}t|dtj}|j|dd|i|j|ddd dd dd dii|j|ddiidS) Nrrrr)rrrrNr)rr)rrN)rr)rrrrK)r@rrrDrDrEtest_cache_changing_keysUs   z(TestWrapNumbers.test_cache_changing_keyscCs\dtdddi}t|dt|dtjd|jtjiiiftjdtjddS)Nrrrz?!?)rrrrKr)r@rrDrDrEtest_cache_clearbs    z TestWrapNumbers.test_cache_clearzno disks or NICs availablecCstjtjtj}x$|D]}|jd||jd|qWtjjtj}x$|D]}|jd||jd|qVWtjjtj}|j|iiifdS)Nzpsutil.disk_io_counterszpsutil.net_io_counters) r4rrrrr6rr=rK)r@ZcachesrrDrDrEtest_cache_clear_public_apisks      z,TestWrapNumbers.test_cache_clear_public_apisN)rrrrtearDownrrrrrrrrrrrrr,skipIfr4rrrrDrDrDrErs" %  0  rzcan't test on TOXzcan't locate scripts directoryc@seZdZdZeddZed=ddZddZej e d d d Z d d Z ddZ ddZddZej epxeoxej dddZddZddZddZej edddZej e d d!d"Zej e d d#d$Zd%d&Zd'd(Zd)d*Zd+d,Z d-d.Z!ej e" d/d0d1Z#d2d3Z$ej e% d ej edd4d5Z&ej e' d ej edd6d7Z(ej e) d ej e* d8d9d:Z+d;d<Z,dS)> TestScriptsz-Tests for scripts in the "scripts" directory.cOsdtjjt|}t|g}x|D]}|j|q Wyt|f|j}Wn8tk r~}zdt |krlt |SWYdd}~XnX|st ||S)Nz%sr?) r;rrtr&rr{r'strip RuntimeErrorrGr)exer|r}cmdargrerrrDrDrE assert_stdouts   zTestScripts.assert_stdoutNc CsRtjjt|}tr"t|ddd}n t|d}||j}WdQRXtj|dS)NZrtutf8)encoding) r;rrtr&r openreadastparse)r r|rsrcrDrDrE assert_syntaxs zTestScripts.assert_syntaxcCsZt|}xLtjtD]>}|jdrdtjj|d|kr|jdtjjt|qWdS)Nz.pyZtest_rzno test defined for %r script) rfr;listdirr&endswithrsplitextrnrt)r@Zmethsr2rDrDrE test_coverages  zTestScripts.test_coveragez POSIX onlycCsTxNtjtD]@}|jdr tjjt|}tjtj|tj@s |j d|q WdS)Nz.pyz%r is not executable) r;rr&rrrtstatS_IXUSRST_MODErn)r@r2rrDrDrEtest_executables  zTestScripts.test_executablecCs|jddS)Nz disk_usage.py)r)r@rDrDrEtest_disk_usageszTestScripts.test_disk_usagecCs|jddS)Nzfree.py)r)r@rDrDrE test_freeszTestScripts.test_freecCs|jddS)Nz meminfo.py)r)r@rDrDrE test_meminfoszTestScripts.test_meminfocCs|jdttjdS)Nz procinfo.py)rrGr;r<)r@rDrDrE test_procinfoszTestScripts.test_procinfoz unreliable on APPVEYOR or TRAVIScCs|jddS)Nzwho.py)r)r@rDrDrEtest_whoszTestScripts.test_whocCs|jddS)Nzps.py)r)r@rDrDrEtest_psszTestScripts.test_pscCs|jddS)Nz pstree.py)r)r@rDrDrE test_pstreeszTestScripts.test_pstreecCs|jddS)Nz netstat.py)r)r@rDrDrE test_netstatszTestScripts.test_netstatzunreliable on TRAVIScCs|jddS)Nz ifconfig.py)r)r@rDrDrE test_ifconfigszTestScripts.test_ifconfigz not supportedcCs|jdttjdS)Nzpmap.py)rrGr;r<)r@rDrDrE test_pmapszTestScripts.test_pmapcCs|jdtddS)Nz procsmem.py)stderr)rr)r@rDrDrE test_procsmemszTestScripts.test_procsmemcCs|jddS)Nz killall.py)r)r@rDrDrE test_killallszTestScripts.test_killallcCs|jddS)Nz nettop.py)r)r@rDrDrE test_nettopszTestScripts.test_nettopcCs|jddS)Nztop.py)r)r@rDrDrEtest_topszTestScripts.test_topcCs|jddS)Nziotop.py)r)r@rDrDrE test_iotopszTestScripts.test_iotopcCs,|jdtjj}|jttj|dS)Nzpidof.py)rr4r5r2r6rGr;r<)r@outputrDrDrE test_pidofszTestScripts.test_pidofz WINDOWS onlycCs|jddS)Nzwinservices.py)r)r@rDrDrEtest_winservicesszTestScripts.test_winservicescCs|jddS)Nzcpu_distribution.py)r)r@rDrDrEtest_cpu_distributionsz!TestScripts.test_cpu_distributioncCs|jddS)Nztemperatures.py)r)r@rDrDrEtest_temperaturesszTestScripts.test_temperaturescCs|jddS)Nzfans.py)r)r@rDrDrE test_fansszTestScripts.test_fansz no batterycCs|jddS)Nz battery.py)r)r@rDrDrE test_batteryszTestScripts.test_batterycCs|jddS)Nz sensors.py)r)r@rDrDrE test_sensorsszTestScripts.test_sensors)N)-rrrrl staticmethodrrrr,rrrrr r!r"r r+r4rr#r$r%r&r'rr(rr*r+r,r-r.r0rr1r2rr3rr4rrr5r6rDrDrDrErs@      rc@sxeZdZejdddZejdddZejdddZejddd Zejdd d Z ejdd d Z dS)TestRetryDecoratorz time.sleepcsFtddddfdd}ttd|j|d|j|jddS)NrrN)retriesrlogfuncsxrjddqWdS)NrNr)poprD)queuerDrErIs z2TestRetryDecorator.test_retry_success..foor)r"listrrK call_count)r@sleeprIrD)r<rEtest_retry_successs z%TestRetryDecorator.test_retry_successcsDtddddfdd}ttd|jt||j|jddS)NrrN)r9rr:csxrjddqWdS)NrNr)r;rD)r<rDrErI&s z2TestRetryDecorator.test_retry_failure..foo)r"r=rrZeroDivisionErrorrKr>)r@r?rIrD)r<rEtest_retry_failure"s  z%TestRetryDecorator.test_retry_failurecCs2ttdddd}|jt||j|jddS)NrN)rrcSstdS)N) TypeErrorrDrDrDrErI3sz2TestRetryDecorator.test_exception_arg..foor)r"rrrDrKr>)r@r?rIrDrDrEtest_exception_arg1s z%TestRetryDecorator.test_exception_argcCs4tdddddd}|jt||j|jddS)Nr)r9rr:cSs dddS)NrNrrDrDrDrDrErI>sz4TestRetryDecorator.test_no_interval_arg..foor)r"rrBrKr>)r@r?rIrDrDrEtest_no_interval_arg:s z'TestRetryDecorator.test_no_interval_argcCs4tdddddd}|jt||j|jddS)NrrN)r9rr:cSs dddS)NrNrrDrDrDrDrErIHsz0TestRetryDecorator.test_retries_arg..foo)r"rrBrKr>)r@r?rIrDrDrEtest_retries_argEs z#TestRetryDecorator.test_retries_argcCs|jttddddS)NrrN)r9Ztimeout)rrr")r@r?rDrDrEtest_retries_and_timeout_argsOsz0TestRetryDecorator.test_retries_and_timeout_argsN) rrrrr8r@rCrErFrGrHrDrDrDrEr8s    r8c@sDeZdZddZddZddZddZd d Zd d Zd dZ dS)TestSyncTestUtilscCs ttdS)N)r%r))r@rDrDrErVszTestSyncTestUtils.tearDownc CsPttjttjd}tjdtdgd|j tj t|WdQRXdS)Nizpsutil.tests.retry.__iter__r)r) r0r;r<maxr4Zpidsrr8iterrr>)r@ZnopidrDrDrEtest_wait_for_pidYs z#TestSyncTestUtils.test_wait_for_pidc Cs>ttd}|jdWdQRXtttjjt s:tdS)NwrI)rr)writer/r;rrr)r@rrDrDrEtest_wait_for_file_s z$TestSyncTestUtils.test_wait_for_filec Cs8ttdWdQRXttddtjjt s4tdS)NrMT)empty)rr)r/r;rrr)r@rDrDrEtest_wait_for_file_emptyes   z*TestSyncTestUtils.test_wait_for_file_emptyc Cs2tjdtdgd|jtttWdQRXdS)Nzpsutil.tests.retry.__iter__r)r)rr8rKrIOErrorr/r))r@rDrDrEtest_wait_for_file_no_fileksz,TestSyncTestUtils.test_wait_for_file_no_filec Cs@ttd}|jdWdQRXttddtjjtsvsz3TestSyncTestUtils.test_call_until..zret == 1rN)r rK)r@rrDrDrEtest_call_untilusz!TestSyncTestUtils.test_call_untilN) rrrrrLrOrQrSrUrWrDrDrDrErITsrIc@s(eZdZddZeZddZddZdS)TestFSTestUtilscCs ttdS)N)r%r))r@rDrDrEr|szTestFSTestUtils.setUpcCsttdjtttjjt s(ttttjttttjjt sTtt j dt t j dd.}|jt ttWdQRX|jstWdQRXdS)NrMzpsutil.tests.os.statr)r3)rr)closer%r;rrrmkdirrr8rrrrr)r@mrDrDrEtest_safe_rmpaths  z TestFSTestUtils.test_safe_rmpathc CsTtj}tjttt |jtjtjj|tWdQRX|jtj|dS)N)r;rrZr)rrKrrt)r@baserDrDrE test_chdirs   $zTestFSTestUtils.test_chdirN)rrrrrr\r^rDrDrDrErXzsrXc@s2eZdZddZddZeje dddZdS) TestProcessUtilscCsRt}tj|j}|jstt|j s2ttjj s@ttjj sNtdS)N) rr4r5r7 is_runningrr r_ _pids_started_subprocesses_started)r@ZsubprBrDrDrEtest_reap_childrens  z#TestProcessUtils.test_reap_childrencCst\}}|j|j|j|js&t|js2ttjjdd}|jt |d|j |||j |||j|j t j |j|j |jt|j st|j sttjj sttjj stdS)NT) recursiver)rrTr7r`rr4r5childrenrKrYr6rOr;r<r r_rarb)r@rUrVrerDrDrEtest_create_proc_children_pairs     z/TestProcessUtils.test_create_proc_children_pairz POSIX onlycCs4t}|jtddtj|}|j|jtjdS)NT)rd)rrr r4r5rKZstatusZ STATUS_ZOMBIE)r@ZzpidrBrDrDrEtest_create_zombie_procs z(TestProcessUtils.test_create_zombie_procN) rrrrcrfr,rrrgrDrDrDrEr_s r_c@sPeZdZddZeje dddZddZeje ddd Z d d Z d S) TestNetUtilsc Cs>t}tjtd|fd}|j|jd|WdQRXdS)Nr)addrrN)r contextlibclosingr rK getsockname)r@ZportrZrDrDrEr szTestNetUtils.bind_socketz POSIX onlycCstz}t|}tj|\|j|jtj|j|jtj |j|j |t j j |s\ttjt j|jsrtWdQRXWdQRXt:}t|tjd}tj||j|jtjWdQRXWdQRXdS)N)type)r-r rjrkrKfamilyrAF_UNIXrmrrlr;rrrrS_ISSOCKst_mode SOCK_DGRAM)r@r2rrDrDrEtest_bind_unix_sockets * z"TestNetUtils.test_bind_unix_socketcCs|dtf}ttj|d\}}tj|Ltj|6|j|j||j|j||j |j|WdQRXWdQRXdS)Nz 127.0.0.1)ri) rr(rAF_INETrjrkrKrl getpeernamerT)r@riserverclientrDrDrEtcp_tcp_socketpairs   zTestNetUtils.tcp_tcp_socketpaircCstj}|j}|jdd s"tt}t|\}}zvtjj |sHtt j tj |j s^t|j |j|d|j t|jddd|j |j||j |j|Wd|j|jXWdQRXdS)NZunix)Zkindr)r4r5num_fdsZ connectionsrr-r.r;rrrrprqrKrYrlrurY)r@rBryr2rvrwrDrDrEtest_unix_socketpairs z!TestNetUtils.test_unix_socketpairc Cst}tjt}tjt}x:|D]2}||jd7<||jtjtjd7<q"W|j |tj dt r|j |tj dt rtr|j |tjd|j |tjd|j |tjdWdQRXdS)NrNr)r collections defaultdictintrnZ getsockoptrZ SOL_SOCKETZSO_TYPEZassertGreaterEqualrtrrrrrorrr)r@ZsocksZfamstypesrZrDrDrEtest_create_socketss    z TestNetUtils.test_create_socketsN) rrrr r,rrrsrxrzrrDrDrDrErhs  rhc@seZdZddZdS)TestOtherUtilscCs0ttjdddddsttt s,tdS)NrIza b crNrr)rr{r^rtuple)r@rDrDrEtest_is_namedtuplesz!TestOtherUtils.test_is_namedtupleN)rrrrrDrDrDrErsr__main__)Nrlrr{rjrrr;rrrr4rrrrrrrrZpsutil._compatr Z psutil.testsr r r r rrrrrrrrrrrrrrrrrrr r!r"r#r$r%r&r'r(r)r*r+r,r-r.r/r0ZTestCaser1r^rrrrrrr8rIrXr_rhrrrrDrDrDrE s                                               I p  C&!&E PK!n%__pycache__/test_linux.cpython-36.pycnu[3 JZ3@sdZddlmZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl Z ddlZddlZddlZddlZddlZddlmZddlmZddlmZddlmZddlmZdd lmZdd lmZdd lmZdd lmZdd lmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddlm$Z$ddlm%Z%ddlm&Z&ddlm'Z'ddlm(Z(ddlm)Z)ddlm*Z*ddlm+Z+ej,j-ej,j.e/Z0dZ1dZ2dZ3erdZ4dd Z5d!d"Z6d#d$Z7d%d&Z8d'd(Z9d)d*Z:e*j;e d+Gd,d-d-e*j<Z=e*j;e d+Gd.d/d/e*j<Z>e*j;e d+Gd0d1d1e*j<Z?e*j;e d+Gd2d3d3e*j<Z@e*j;e d+Gd4d5d5e*j<ZAe*j;e d+Gd6d7d7e*j<ZBe*j;e d+Gd8d9d9e*j<ZCe*j;e d+e*j;e d:Gd;d<dd>e*j<ZEe*j;e d+Gd?d@d@e*j<ZFe*j;e d+GdAdBdBe*j<ZGe*j;e d+GdCdDdDe*j<ZHe*j;e d+GdEdFdFe*j<ZIeJdGkre#e/dS)HzLinux specific tests.)divisionN)LINUX)PY3)u) call_until) HAS_BATTERY) HAS_CPU_FREQ) HAS_RLIMIT)MEMORY_TOLERANCE)mock)PYPY)pyrun) reap_children) reload_module)retry_before_failing)run_test_module_by_name) safe_rmpath)sh)skip_on_not_implemented)TESTFN) ThreadTask)TRAVIS)unittest)whichiii'icCspddl}|dd}tr"t|d}tjtjtj}tj|*tj|j |j t t j d|ddSQRXdS)Nrascii256s)fcntlrbytessocketAF_INET SOCK_DGRAM contextlibclosingZ inet_ntoaioctlfileno SIOCGIFADDRstructpack)ifnamersr-"/usr/lib64/python3.6/test_linux.pyget_ipv4_address@s    r/c sddl}|dd}tr"t|d}tjtjtj}tj|`|j|j t t j d|}trfddnddl }|jdjfdd |d d Ddd SQRXdS)NrrrrcSs|S)Nr-)xr-r-r.ordWszget_mac_address..ordcsg|]}d|qS)z%02x:r-).0char)r1r-r. \sz#get_mac_address..r)rrr r!r"r#r$r%r&r' SIOCGIFHWADDRr)r* __builtin__r1join)r+rr,infor:r-)r1r.get_mac_addressMs    r=cCsttd}|jd}xJ|D]B}|jdr|j\}}}}tjdd}|t|t|t|SqWtddj|dS)zQParse 'free' cmd and return swap memory's s total, used and free values. zfree -b ZSwapfreeztotal used freez&can't find 'Swap' in 'free' output: %sN)rsplit startswith collections namedtupleint ValueErrorr;)outlinesline_totalusedr?ntr-r-r. free_swap_s    rMcCs~td}|jd}xT|D]L}|jdrdd|jddD\}}}}tjdd }||||||SqWtd dj|d S) zSParse 'free' cmd and return physical memory's total, used and free values. zfree -br>ZMemcSsg|] }t|qSr-)rD)r3r0r-r-r.r5{sz free_physmem..r7r?ztotal used free shared outputz%can't find 'Mem' in 'free' output: %sN)rr@rArBrCrEr;)rFrGrHrJrKr?sharedrLr-r-r. free_physmemns   "rPcCsNtd}x4|jdD]&}|j}||krt|jddSqWtd|dS)Nz vmstat -sr> rz can't find %r in 'vmstat' output)rr@striprDrE)statrFrHr-r-r.vmstats rTcCs(tdj}ttt|jdjdS)Nzfree -Vr7.r8)rrRtuplemaprDr@)rFr-r-r.get_free_version_infos rXz LINUX onlyc@seZdZddZejeo ed kdeddZ eje ded d Z ed d Z eje ded dZ eje deddZeddZeddZddZddZddZddZddZdS)!TestSystemVirtualMemorycCs&tdd}tjj}|j||dS)Nz total memoryi)rTpsutilvirtual_memoryrJassertAlmostEqual)self vmstat_value psutil_valuer-r-r. test_totals  z"TestSystemVirtualMemory.test_total zold free versioncCs8t}|j}tjj}|j||td|||jfddS)Nz %s %s %s)deltamsg)rPrKrZr[r\r output)r]r? free_valuer_r-r-r. test_useds  z!TestSystemVirtualMemory.test_usedzunreliable on TRAVIScCs*tdd}tjj}|j||tddS)Nz free memoryi)rc)rTrZr[r?r\r )r]r^r_r-r-r. test_frees  z!TestSystemVirtualMemory.test_freecCs*tdd}tjj}|j||tddS)Nz buffer memoryi)rc)rTrZr[buffersr\r )r]r^r_r-r-r. test_bufferss  z$TestSystemVirtualMemory.test_bufferscCs*tdd}tjj}|j||tddS)Nz active memoryi)rc)rTrZr[activer\r )r]r^r_r-r-r. test_actives  z#TestSystemVirtualMemory.test_activecCs*tdd}tjj}|j||tddS)Nzinactive memoryi)rc)rTrZr[inactiver\r )r]r^r_r-r-r. test_inactives  z%TestSystemVirtualMemory.test_inactivecCsJt}|j}|dkrtjdtjj}|j||td|||jfddS)Nrz%free does not support 'shared' columnz %s %s %s)rcrd) rPrOrSkipTestrZr[r\r re)r]r?rfr_r-r-r. test_shareds  z#TestSystemVirtualMemory.test_sharedcCshtd}|jd}d|dkr*tjdn:t|djd }tjj}|j||t d|||fddS) Nzfree -br> availablerz(free does not support 'available' columnr7z %s %s %s)rcrdr8) rr@rrorDrZr[rqr\r )r]rFrGrfr_r-r-r.test_availables    z&TestSystemVirtualMemory.test_availablecsnfdd}ttrdnd}tj|d|d6}tjdd}tjdtj}|j s\t |j t |d |d }|j jd st |jd t|j|jd t|j|jdt|j|jdt|j|jdt|j|jdt|j|jdt|j|j |jd |j |jd |j |jd |j |jd |j |jd |j |jd WdQRXWdQRXdS)Ncs0|dkrtjtjdjS|f||SdS)Nz /proc/meminfoa Active(anon): 6145416 kB Active(file): 2950064 kB Inactive(anon): 574764 kB Inactive(file): 1567648 kB MemAvailable: -1 kB MemFree: 2057400 kB MemTotal: 16325648 kB SReclaimable: 346648 kB )ioBytesIOtextwrapdedentencode)nameargskwargs) orig_openr-r. open_mocks zBTestSystemVirtualMemory.test_warnings_on_misses..open_mockz builtins.openz__builtin__.openT)create side_effect)recordalwaysr7rzpsutil/_pslinux.pyz#memory stats couldn't be determinedcachedrOrkrmrirq)openrr patchwarningscatch_warnings simplefilterrZr[calledAssertionError assertEquallenfilenameendswithassertInstrmessagerrkrmrOrirq)r]r| patch_pointmwsretwr-)r{r.test_warnings_on_missess2    z/TestSystemVirtualMemory.test_warnings_on_missesc Csddlm}ddlm}i}|d4}x,|D]$}|j}t|dd||d<q,WWdQRX||}d|kr|d}t|||d} |j| d dS) Nr)calculate_avail_vmem) open_binaryz /proc/meminfor7is MemAvailable:d )psutil._pslinuxrrr@rDabsZ assertLess) r]rrZmemsfrHfieldsabZ diff_percentr-r-r.test_avail_old_percents    &z.TestSystemVirtualMemory.test_avail_old_percentcsfdd}ttrdnd}tj|d|dX}tjdd}tj}WdQRX|jsXt |j |j d |d }|j d t |jWdQRXdS) Ncs0|dkrtjtjdjS|f||SdS)Nz /proc/meminfoa Active: 9444728 kB Active(anon): 6145416 kB Active(file): 2950064 kB Buffers: 287952 kB Cached: 4818144 kB Inactive(file): 1578132 kB Inactive(anon): 574764 kB Inactive(file): 1567648 kB MemAvailable: 6574984 kB MemFree: 2057400 kB MemTotal: 16325648 kB Shmem: 577588 kB SReclaimable: 346648 kB )rsrtrurvrw)rxryrz)r{r-r.r|0s zKTestSystemVirtualMemory.test_avail_old_comes_from_kernel..open_mockz builtins.openz__builtin__.openT)r}r~)riSdirz,inactive memory stats couldn't be determinedl ")rrr rrrrZr[rrrrqrrr)r]r|rrrrrr-)r{r. test_avail_old_comes_from_kernel-s   z8TestSystemVirtualMemory.test_avail_old_comes_from_kernelcsfdd}ttrdnd}tj|d|dX}tjdd}tj}WdQRX|jsXt |j |j d|d }|j d t |jWdQRXdS)Ncs0|dkrtjtjdjS|f||SdS)Nz /proc/meminfoa Active: 9444728 kB Active(anon): 6145416 kB Buffers: 287952 kB Cached: 4818144 kB Inactive(file): 1578132 kB Inactive(anon): 574764 kB MemFree: 2057400 kB MemTotal: 16325648 kB Shmem: 577588 kB )rsrtrurvrw)rxryrz)r{r-r.r|Ss zHTestSystemVirtualMemory.test_avail_old_missing_fields..open_mockz builtins.openz__builtin__.openT)r}r~)ridiiIrz,inactive memory stats couldn't be determinedi}l'Ll`LG)rrr rrrrZr[rrrrqrrr)r]r|rrrrrr-)r{r.test_avail_old_missing_fieldsOs   z5TestSystemVirtualMemory.test_avail_old_missing_fieldscsfdd}ttrdnd}tj|d|dX}tjdd}tj}WdQRX|jsXt |j |j d|d }|j d t |jWdQRXdS)NcsF|dkrtjtjdjS|dkr2ttjdn|f||SdS)Nz /proc/meminfoaT Active: 9444728 kB Active(anon): 6145416 kB Active(file): 2950064 kB Buffers: 287952 kB Cached: 4818144 kB Inactive(file): 1578132 kB Inactive(anon): 574764 kB Inactive(file): 1567648 kB MemFree: 2057400 kB MemTotal: 16325648 kB Shmem: 577588 kB SReclaimable: 346648 kB z/proc/zoneinfozno such file or directory)rsrtrurvrwIOErrorerrnoENOENT)rxryrz)r{r-r.r|qs  zJTestSystemVirtualMemory.test_avail_old_missing_zoneinfo..open_mockz builtins.openz__builtin__.openT)r}r~)ridiiIrz,inactive memory stats couldn't be determinedi}l'Ll`LG)rrr rrrrZr[rrrrqrrr)r]r|rrrrrr-)r{r.test_avail_old_missing_zoneinfons   z7TestSystemVirtualMemory.test_avail_old_missing_zoneinfoN)rararb)__name__ __module__ __qualname__r`rskipIfrrXrrgrrhrjrlrnrprrrrrrrr-r-r-r.rYs$      ,"rYc@s\eZdZeddZddZeddZeddZd d Z d d Z d dZ ddZ dS)TestSystemSwapMemoryc Cs,td}|j}WdQRXd|ko*d|kS)z3Return True if /proc/meminfo provides swap metrics.z /proc/meminfoNz SwapTotal:z SwapFree:)rread)rdatar-r-r.meminfo_has_swap_infos z*TestSystemSwapMemory.meminfo_has_swap_infocCs"tj}tjj}|j||tdS)N)rc)rMrJrZ swap_memoryr\r )r]rfr_r-r-r.r`s zTestSystemSwapMemory.test_totalcCs"tj}tjj}|j||tdS)N)rc)rMrKrZrr\r )r]rfr_r-r-r.rgs zTestSystemSwapMemory.test_usedcCs"tj}tjj}|j||tdS)N)rc)rMr?rZrr\r )r]rfr_r-r-r.rhs zTestSystemSwapMemory.test_freecCstjddd}tjddx}tjdtj}|js:t|j t |d|d}|j j dsbt|j d t|j|j |jd|j |jdWdQRXWdQRXdS) Nzpsutil._pslinux.openT)r})rrr7rzpsutil/_pslinux.pyz9'sin' and 'sout' swap memory stats couldn't be determined)r rrrrrZrrrrrrrrrrsinsout)r]rrrrr-r-r.test_missing_sin_souts   z*TestSystemSwapMemory.test_missing_sin_soutcsfdd}ttrdnd}tj|d|d}tjddx}tjdtj}|j sXt |j t |d |d }|j jd st |jd t|j|j |jd |j |jd WdQRXWdQRXdS) Ncs*|dkrttjdn|f||SdS)Nz /proc/vmstatzno such file or directory)rrr)rxryrz)r{r-r.r|sz=TestSystemSwapMemory.test_no_vmstat_mocked..open_mockz builtins.openz__builtin__.openT)r}r~)rrr7rzpsutil/_pslinux.pyzK'sin' and 'sout' swap memory stats couldn't be determined and were set to 0)rrr rrrrrZrrrrrrrrrrrr)r]r|rrrrrr-)r{r.test_no_vmstat_mockeds      z*TestSystemSwapMemory.test_no_vmstat_mockedcCs|jstjdStjd}tj}WdQRX|j s.open_mockz builtins.openz__builtin__.openT)r}r~)rrr rrZrrr)r]r|rrr-)r{r.#test_emulate_meminfo_has_no_metricss   z8TestSystemSwapMemory.test_emulate_meminfo_has_no_metricsN) rrr staticmethodrr`rrgrhrrrrr-r-r-r.rs rc@s&eZdZejedddZejejj d dddZ ejejj d d d d Z eje d  d ddZ eje d dddZddZddZeje dddZejedeje dddZeje dddZeje dd d!Zejedeje dd"d#Zd$S)% TestSystemCPUzunknown failure on traviscCstjj}tjdtjdd}ttt |j d}|d krL|j d|n |j d||d krn|j d |n |j d ||dkr|j d |n |j d |dS)Nz \d+\.\d+\.\d+rrU ZstealrZguestraZ guest_nice)rrr)rrr)rarr) rZ cpu_times_fieldsrefindallosunamerVrWrDr@r assertNotIn)r]rZ kernel_verZkernel_ver_infor-r-r.test_cpu_timess   zTestSystemCPU.test_cpu_timesz/sys/devices/system/cpu/onlinez-/sys/devices/system/cpu/online does not existc CsVtd}|jj}WdQRXdt|krRt|jddd}|jtj|dS)Nz/sys/devices/system/cpu/online-r7) rrrRrrDr@rrZ cpu_count)r]rvaluer-r-r.*test_cpu_count_logical_w_sysdev_cpu_onlines   z8TestSystemCPU.test_cpu_count_logical_w_sysdev_cpu_onlinez/sys/devices/system/cpuz&/sys/devices/system/cpu does not existcCs0tjd}tdd|D}|jtj|dS)Nz/sys/devices/system/cpucSs g|]}tjd|dk r|qS)zcpu\d+$N)rsearch)r3r0r-r-r.r5%szITestSystemCPU.test_cpu_count_logical_w_sysdev_cpu_num..)rlistdirrrrZr)r]Zlscountr-r-r.'test_cpu_count_logical_w_sysdev_cpu_num!s z5TestSystemCPU.test_cpu_count_logical_w_sysdev_cpu_numZnprocznproc utility not availablecCs$ttd}|jtjdd|dS)Nz nproc --allT)logical)rDrrrZr)r]numr-r-r.test_cpu_count_logical_w_nproc(s z,TestSystemCPU.test_cpu_count_logical_w_nprocZlscpuzlscpu utility not availablecCs8td}tdd|jdD}|jtjdd|dS)Nzlscpu -pcSsg|]}|jds|qS)#)rA)r3r0r-r-r.r50sz@TestSystemCPU.test_cpu_count_logical_w_lscpu..r>T)r)rrr@rrZr)r]rFrr-r-r.test_cpu_count_logical_w_lscpu-sz,TestSystemCPU.test_cpu_count_logical_w_lscpuc &s<ddl}|jj}tjdtd}|j|jj||js@ttjddd:}|j |jj|j|j d|j|j dddWdQRXt d d }|j }WdQRXtj|}tjd|dd }|j|jj|WdQRXfd d }t trdnd}tj||dd|j|jj|WdQRXWdQRXdS)Nrzpsutil._pslinux.os.sysconf)r~zpsutil._pslinux.openT)r}rz /proc/statz /proc/cpuinforb) return_valuer}cs(|jdrtjdS|f||SdS)Nz /proc/cpuinfor)rArsrt)rxryrz)r{r-r.r|Ps  z>TestSystemCPU.test_cpu_count_logical_mocked..open_mockz builtins.openz__builtin__.open)r~r})r_pslinuxZcpu_count_logicalr rrErrr assertIsNoneZ call_count call_argsrrrsrtr) r]rZoriginalrrZ cpuinfo_data fake_filer|rr-)r{r.test_cpu_count_logical_mocked3s*        z+TestSystemCPU.test_cpu_count_logical_mockedc Cs8tjddd }|jtjj|js*tWdQRXdS)Nzpsutil._pslinux.openT)r})r rrrZrZcpu_count_physicalrr)r]rr-r-r.test_cpu_count_physical_mocked[sz,TestSystemCPU.test_cpu_count_physical_mockedz not supportedc Cs,tjdgd|jtjWdQRXdS)Nzpsutil._pslinux.glob.glob)r)r rrrZcpu_freq)r]r-r-r.test_cpu_freq_no_resultbsz%TestSystemCPU.test_cpu_freq_no_resultzfails on Travisc sTfdd}gtjtjd|dd"tjs6t|jtdWdQRXdS)Ncs.|jdrjdgSjd|SdS)Nz&/sys/devices/system/cpu/cpufreq/policy)rAappend)pattern)flags orig_globr-r. glob_mockks    z>TestSystemCPU.test_cpu_freq_use_second_file..glob_mockzpsutil._pslinux.glob.globT)r~r}r)globr rrZrrrr)r]rr-)rrr.test_cpu_freq_use_second_filegs  z+TestSystemCPU.test_cpu_freq_use_second_filecsfdd}ttrdnd}tj||dTtjddgd8tj}|j|jd |j|jd |j|j d WdQRXWdQRXdS) NcsP|jdrtjdS|jdr(tjdS|jdr.open_mockz builtins.openz__builtin__.open)r~z glob.globz'/sys/devices/system/cpu/cpufreq/policy0)rg@@g@g@) rrr rrZrrcurrentminmax)r]r|rfreqr-)r{r.test_cpu_freq_emulate_datazs   z(TestSystemCPU.test_cpu_freq_emulate_datacsfdd}ttrdnd}dddg}tj||dRtjd |d 8tj}|j|jd |j|jd |j|j d WdQRXWdQRXdS)NcsP|jdrtjdS|jdr(tjdS|jdr.open_mockz builtins.openz__builtin__.openz'/sys/devices/system/cpu/cpufreq/policy0z'/sys/devices/system/cpu/cpufreq/policy1z'/sys/devices/system/cpu/cpufreq/policy2)r~z glob.glob)rgY@gi@gr@) rrr rrZrrrrr)r]r|rpoliciesrr-)r{r.test_cpu_freq_emulate_multi_cpus  z-TestSystemCPU.test_cpu_freq_emulate_multi_cpucsfdd}ttrdnd}dddg}tj||d6tjd |d tj}|j|jd WdQRXWdQRXfd d}ttrdnd}tj||d.tjd |d |jt tjWdQRXWdQRXdS) Ncs@|jdrttjdn$|jdr,tjdS|f||SdS)Nz/scaling_cur_freqr2z/cpuinfo_cur_freqs200000)rrrrrsrt)rxryrz)r{r-r.r|s    zGTestSystemCPU.test_cpu_freq_no_scaling_cur_freq_file..open_mockz builtins.openz__builtin__.openz'/sys/devices/system/cpu/cpufreq/policy0z'/sys/devices/system/cpu/cpufreq/policy1z'/sys/devices/system/cpu/cpufreq/policy2)r~z glob.glob)rcsD|jdrttjdn(|jdr0ttjdn|f||SdS)Nz/scaling_cur_freqr2z/cpuinfo_cur_freq)rrrr)rxryrz)r{r-r.r|s   ) rrr rrZrrr assertRaisesNotImplementedError)r]r|rrrr-)r{r.&test_cpu_freq_no_scaling_cur_freq_files   "  z4TestSystemCPU.test_cpu_freq_no_scaling_cur_freq_fileN)rrrrrrrrpathexistsrrrrrrrrrrrrrr-r-r-r.rs (  rc@s4eZdZejedddZejedddZdS)TestSystemCPUStatszfails on TraviscCs&td}tjj}|j||dddS)Nzcontext switchesi)rc)rTrZ cpu_statsZ ctx_switchesr\)r]r^r_r-r-r.test_ctx_switchess z$TestSystemCPUStats.test_ctx_switchescCs&td}tjj}|j||dddS)N interruptsi)rc)rTrZrrr\)r]r^r_r-r-r.test_interruptss z"TestSystemCPUStats.test_interruptsN)rrrrrrrrr-r-r-r.rsrc@s|eZdZddZddZeddZeje d deje d d d Z e j d ed e j dddddZddZdS)TestSystemNetworkcCsjxdtjjD]T\}}xJ|D]B}|jtjkr@|j|jt|q|jtj kr|j|jt |qWqWdS)N) rZ net_if_addrsitemsZfamilyZAF_LINKrZaddressr=r!r"r/)r]rxZaddrsZaddrr-r-r.test_net_if_addrs_ipss    z'TestSystemNetwork.test_net_if_addrs_ipscCsbx\tjjD]L\}}ytd|}Wntk r:YqX|j|jttj d|dqWdS)Nz ifconfig %sz(?i)MTU[: ](\d+)r) rZ net_if_statsrr RuntimeErrorrZmturDrr)r]rxstatsrFr-r-r.test_net_if_statssz#TestSystemNetwork.test_net_if_statscsfdd}tjddd}x|jD]\}y |}Wntk rNw$YnX|j|j|ddd |j|j|d dd |j|j|d dd |j|j|d dd |j|j |d dd |j|j |ddd |j|j |ddd |j|j |ddd q$WdS)Ncsi}td}ttjd|d|d<ttjd|d|d<ttjd|d|d<ttjd|d |d <ttjd |d|d <ttjd |d |d <ttjd|d|d<ttjd|d|d<|S)Nz ifconfig %szRX packets[: ](\d+)r packets_recvzTX packets[: ](\d+) packets_sentzerrors[: ](\d+)errinr7erroutzdropped[: ](\d+)dropindropoutz#RX (?:packets \d+ +)?bytes[: ](\d+) bytes_recvz#TX (?:packets \d+ +)?bytes[: ](\d+) bytes_sent)rrDrr)ZnicrrF)rxr-r.ifconfigs z8TestSystemNetwork.test_net_io_counters..ifconfigTF)ZpernicnowraprirN)rcrrrrrrrrii) rZnet_io_countersrrr\rrrrrrrr)r]rZniorZ ifconfig_retr-)rxr.test_net_io_counterss.  z&TestSystemNetwork.test_net_io_countersZipz'ip' utility not availablezskipped on TraviscCstdj}ddtjjD}d}xL|jdD]>}|j}tjd|r2|d7}|jddj}|j||q2W|j t ||d t j ||fd dS) Nzip addrcSsg|]}d|kr|qS):r-)r3r0r-r-r.r52sz7TestSystemNetwork.test_net_if_names..rr>z^\d+:r7r z %s --- %s)rd) rrRrZrkeysr@rrrrrpprintZpformat)r]rFZnicsfoundrHrxr-r-r.test_net_if_names.s  z#TestSystemNetwork.test_net_if_namesz psutil._pslinux.socket.inet_ntop)r~zpsutil._pslinux.supports_ipv6F)rc CsRy*tjtjtj}|j|j|jdWntjk r@YnXtjdddS)N::1rZinet6)kind)rr) r!ZAF_INET6Z SOCK_STREAM addCleanupcloseZbinderrorrZnet_connections)r]Z supports_ipv6Z inet_ntopr,r-r-r.%test_net_connections_ipv6_unsupported=s z7TestSystemNetwork.test_net_connections_ipv6_unsupportedc sPfdd}ttrdnd}tj||d}tjdd|jsBtWdQRXdS)Ncs,|dkrtjtjdS|f||SdS)Nz/proc/net/unixaB 0: 00000003 000 000 0001 03 462170 @/tmp/dbus-Qw2hMPIU3n 0: 00000003 000 000 0001 03 35010 @/tmp/dbus-tB2X8h69BQ 0: 00000003 000 000 0001 03 34424 @/tmp/dbus-cHy80Y8O 000000000000000000000000000000000000000000000000000000 )rsStringIOrurv)rxryrz)r{r-r.r|Jsz@TestSystemNetwork.test_net_connections_mocked..open_mockz builtins.openz__builtin__.open)r~Zunix)r)rrr rrZrrr)r]r|rrr-)r{r.test_net_connections_mockedIs    z-TestSystemNetwork.test_net_connections_mockedN)rrrrrrr rrrrrr rrErrr-r-r-r.rs  *  rc@sNeZdZejeed deddZddZ ddZ d d Z d d Z d S)TestSystemDisksstatvfszos.statvfs() not availablecCsdd}xtjddD]|}tj|j}||j\}}}}|j|j|t|j|d krl|jd|j|ft|j |d kr|jd|j |fqWdS) NcSsztd|j}|jd}|jd|jd}|jdd\}}}}|dkrRd}t|t|t|}}}||||fS)Nzdf -P -B 1 "%s"r>rZnoner2)rrRr@poprD)rrFrGrHdevrJrKr?r-r-r.dfis   z:TestSystemDisks.test_disk_partitions_and_usage..dfF)allrizpsutil=%s, df=%si(ii(i) rZdisk_partitionsZ disk_usageZ mountpointrrJrr?failrK)r]rpartZusagerrJrKr?r-r-r.test_disk_partitions_and_usageds  z.TestSystemDisks.test_disk_partitions_and_usagecCstdd}|j}WdQRXd|krPxtjD]}|jdkr0Pq0W|jdn|tjtd}t j d|ddX}t j d dgd <}tj}|j st |j st |st |j |djdWdQRXWdQRXdS)Nz/proc/filesystemsrzfszcouldn't find any ZFS partitionz nodev zfs zpsutil._pslinux.openT)rr}z$psutil._pslinux.cext.disk_partitions /dev/sdb3/rw)rr)r&r'r%r()rrrZr Zfstyper!rsrrr rrrr)r]rrr"rm1m2rr-r-r.test_disk_partitions_mocked~s$       z+TestSystemDisks.test_disk_partitions_mockedc sfdd}ttrdnd}tj||d}tjdd}|jsBt|j|j d|j|j d |j|j d t |j|j d |j|jd |j|jd |j|jdt |j|jd|j|jdWdQRXdS)NcsB|dkrtjtjdS|dkr.tjtdS|f||SdS)Nz/proc/partitionszu major minor #blocks name 8 0 488386584 hda z/proc/diskstatsz+ 3 0 1 hda 2 3 4 5 6 7 8 9 10 11 12)rsrrurvr)rxryrz)r{r-r.r|s zJTestSystemDisks.test_disk_io_counters_kernel_2_4_mocked..open_mockz builtins.openz__builtin__.open)r~F)rr7rrarrNrr)rrr rrZdisk_io_countersrrr read_countread_merged_count read_bytes SECTOR_SIZE read_time write_countwrite_merged_count write_bytes write_time busy_time)r]r|rrrr-)r{r.'test_disk_io_counters_kernel_2_4_mockeds    z7TestSystemDisks.test_disk_io_counters_kernel_2_4_mockedc sfdd}ttrdnd}tj||d}tjdd}|jsBt|j|j d|j|j d |j|j d t |j|j d |j|jd |j|jd |j|jdt |j|jd|j|jdWdQRXdS)NcsB|dkrtjtjdS|dkr.tjtdS|f||SdS)Nz/proc/partitionszu major minor #blocks name 8 0 488386584 hda z/proc/diskstatsz' 3 0 hda 1 2 3 4 5 6 7 8 9 10 11)rsrrurvr)rxryrz)r{r-r.r|s zOTestSystemDisks.test_disk_io_counters_kernel_2_6_full_mocked..open_mockz builtins.openz__builtin__.open)r~F)rr7rrarrNrr,r-r)rrr rrZr.rrrr/r0r1r2r3r4r5r6r7r8)r]r|rrrr-)r{r.,test_disk_io_counters_kernel_2_6_full_mockeds    z.open_mockz builtins.openz__builtin__.open)r~F)rr7rrarr)rrr rrZr.rrrr/r1r2r4r6r0r3r5r7r8)r]r|rrrr-)r{r./test_disk_io_counters_kernel_2_6_limited_mockeds    z?TestSystemDisks.test_disk_io_counters_kernel_2_6_limited_mockedN) rrrrrhasattrrrr#r+r9r:r;r-r-r-r.ras  rc@sVeZdZddZejdddZddZdd Zd d Z d d Z ddZ ddZ dS)TestMisccCs(td}tj}|jt|t|dS)Nz boot time)rTrZ boot_timerrD)r]r^r_r-r-r.test_boot_timeszTestMisc.test_boot_timezpsutil.traceback.print_excc"stj}ttjj|dd$}|jd|jd|jdWdQRXztfdd}trbdnd }tj ||d xt t |j st |jtt j|jtt jd d |jtt j|jtt jd d |jtt j|jtt jd d |t _|jt jd |jtt jd t jd d }|jt|d t jd d }|jttt|d ttjj|dd$}|jd|jd|jdWdQRX|jt jd |jtt jd d d |jtt jd |jtttt jd d d WdQRXWdtj|t t X|jt jddS)NrSrzcpu 0 0 0 0 0 0 0 0 0 0 zcpu0 0 0 0 0 0 0 0 0 0 0 zcpu1 0 0 0 0 0 0 0 0 0 0 cs&|jdrttjd|f||S)Nz/proczrejecting access for test)rArrr)rxryrz)r{r-r.r|s  z4TestMisc.test_no_procfs_on_import..open_mockz builtins.openz__builtin__.open)r~T)percpurzcpu 1 0 0 0 0 0 0 0 0 0 zcpu0 1 0 0 0 0 0 0 0 0 0 zcpu1 1 0 0 0 0 0 0 0 0 0 z/proc)tempfilemkdtemprrrr;writerr rrrZrrrrrZ cpu_percentZcpu_times_percent PROCFS_PATHrsumrWZassertNotEqualshutilZrmtree)r]tbZ my_procfsrr|rZper_cpu_percentZper_cpu_times_percentr-)r{r.test_no_procfs_on_importsN         (  z!TestMisc.test_no_procfs_on_importc Cs8tjddd }|jttjj|js*tWdQRXdS)Nzpsutil._pslinux.openT)r}) r rrrrZrr>rr)r]rr-r-r.test_boot_time_mockedDs  zTestMisc.test_boot_time_mockedcCstjdd gd&}|jtjd jd |js2tWdQRXtjddgd&}|jtjd jd |jsntWdQRXtjddgd&}|jtjd jd |jstWdQRXdS)Nzpsutil._pslinux.cext.users giampaolopts/2:0hATr)rrZ localhost:0.0foo)rJrKrLrMTr)rJrKrNrMTr)rJrKrOrMTr)r rrrZZusershostrr)r]rr-r-r.test_users_mockedKs   zTestMisc.test_users_mockedc Cstj}z|t_|jttj|jttj|jttjdd|jttj|jttj |jttj |jttj |jttj |jttj |jtjtjWddt_tj|XdS)NT)r@z/proc)rArBrZrDrrr[rr>rr rr.r Z NoSuchProcessProcessrrmdir)r]Ztdirr-r-r.test_procfs_path_szTestMisc.test_procfs_pathc sPfdd}gttrdnd}tj||dtjsBtWdQRXdS)NcsJtrt|tr|j}d|kr6jdttjdn|f||SdS)NZhw_sector_sizer2)r isinstancer decoderrrr)rxryrz)flagr{r-r.r|us  z1TestMisc.test_sector_size_mock..open_mockz builtins.openz__builtin__.open)r~)rrr rrZr.r)r]r|rr-)rWr{r.test_sector_size_mockrs  zTestMisc.test_sector_size_mockc Csnt}|jzPtj}|jdj}tj| s:t|tj|}|j|j |tj Wd|j XdS)Nr7) rstartrZrRthreadsid pid_existsrZas_dictrZpidsstop)r]tptidZptr-r-r.test_issue_687s zTestMisc.test_issue_687c sLfdd}ttrdnd}tj||dtjtjs>tWdQRXdS)Ncs2|dtjkrtjtdS|f||SdS)Nz/proc/%s/statusr2)rgetpidrsrr)rxryrz)r{r-r.r|sz:TestMisc.test_pid_exists_no_proc_status..open_mockz builtins.openz__builtin__.open)r~) rrr rrZr\rrbr)r]r|rr-)r{r.test_pid_exists_no_proc_statuss   z'TestMisc.test_pid_exists_no_proc_statusN) rrrr?r rrHrIrQrTrXrarcr-r-r-r.r=s>r=z no batteryc@seZdZejed dddZejed dddZddZd d Z d d Z d dZ ddZ ddZ ddZddZddZddZdS)TestSensorsBatteryZacpizacpi utility not availablecCsDtd}t|jddjjdd}tjj}|j||dddS)Nzacpi -b,r7%r2)rc) rrDr@rRreplacerZsensors_batterypercentr\)r]rFZ acpi_valuer_r-r-r. test_percents zTestSensorsBattery.test_percentcCsTtd}d|jkrtjdSd|kr,d}nd|jddk}|jtjj|dS) Nzacpi -bunknownzacpi output not reliablezdischarging at zero rateTZChargingr>r) rlowerrrr@rrZrh power_plugged)r]rFZpluggedr-r-r.test_power_pluggeds  z%TestSensorsBattery.test_power_pluggedc sjfdd}ttrdnd}tj||d6}|jtjjd|jtjjtj |j s\t WdQRXdS)Ncs2|jds|jdrtjdS|f||SdS)Nz AC0/onlinez AC/online1)rrsrt)rxryrz)r{r-r.r|s z@TestSensorsBattery.test_emulate_power_plugged..open_mockz builtins.openz__builtin__.open)r~T) rrr rrrZrhrmZsecsleftZPOWER_TIME_UNLIMITEDrr)r]r|rrr-)r{r.test_emulate_power_pluggeds  z-TestSensorsBattery.test_emulate_power_pluggedc sVfdd}ttrdnd}tj||d"}|jtjjd|jsHt WdQRXdS)NcsN|jds|jdr"ttjdn(|jdr:tjtdS|f||SdS)Nz AC0/onlinez AC/onliner2z/statusZcharging)rrrrrsrr)rxryrz)r{r-r.r|s  zBTestSensorsBattery.test_emulate_power_plugged_2..open_mockz builtins.openz__builtin__.open)r~T) rrr rrrZrhrmrr)r]r|rrr-)r{r.test_emulate_power_plugged_2s   z/TestSensorsBattery.test_emulate_power_plugged_2c sVfdd}ttrdnd}tj||d"}|jtjjd|jsHt WdQRXdS)Ncs2|jds|jdrtjdS|f||SdS)Nz AC0/onlinez AC/online0)rrsrt)rxryrz)r{r-r.r|s zDTestSensorsBattery.test_emulate_power_not_plugged..open_mockz builtins.openz__builtin__.open)r~F) rrr rrrZrhrmrr)r]r|rrr-)r{r.test_emulate_power_not_pluggeds   z1TestSensorsBattery.test_emulate_power_not_pluggedc sVfdd}ttrdnd}tj||d"}|jtjjd|jsHt WdQRXdS)NcsN|jds|jdr"ttjdn(|jdr:tjtdS|f||SdS)Nz AC0/onlinez AC/onliner2z/statusZ discharging)rrrrrsrr)rxryrz)r{r-r.r|s  zFTestSensorsBattery.test_emulate_power_not_plugged_2..open_mockz builtins.openz__builtin__.open)r~F) rrr rrrZrhrmrr)r]r|rrr-)r{r. test_emulate_power_not_plugged_2s   z3TestSensorsBattery.test_emulate_power_not_plugged_2c sTfdd}ttrdnd}tj||d }|jtjj|jsFt WdQRXdS)NcsJ|jds|jdr"ttjdn$|jdr6tjdS|f||SdS)Nz"/sys/class/power_supply/AC0/onlinez!/sys/class/power_supply/AC/onliner2z#/sys/class/power_supply/BAT0/statuss???)rArrrrsrt)rxryrz)r{r-r.r|s     zETestSensorsBattery.test_emulate_power_undetermined..open_mockz builtins.openz__builtin__.open)r~) rrr rrrZrhrmrr)r]r|rrr-)r{r.test_emulate_power_undetermineds   z2TestSensorsBattery.test_emulate_power_undeterminedc sRfdd}ttrdnd}tj||d}|jtj|jsDtWdQRXdS)Ncs6|jds|jdr"ttjdn|f||SdS)Nz'/sys/class/power_supply/BAT0/energy_nowz'/sys/class/power_supply/BAT0/charge_nowr2)rArrr)rxryrz)r{r-r.r|s  z@TestSensorsBattery.test_emulate_no_base_files..open_mockz builtins.openz__builtin__.open)r~) rrr rrrZrhrr)r]r|rrr-)r{r.test_emulate_no_base_filess   z-TestSensorsBattery.test_emulate_no_base_filesc sVfdd}ttrdnd}tj||d"}|jtjjd|jsHt WdQRXdS)Ncs(|jdrtjdS|f||SdS)Nz(/sys/class/power_supply/BAT0/energy_fullrr)rArsrt)rxryrz)r{r-r.r|&s  z@TestSensorsBattery.test_emulate_energy_full_0..open_mockz builtins.openz__builtin__.open)r~r) rrr rrrZrhrirr)r]r|rrr-)r{r.test_emulate_energy_full_0$s   z-TestSensorsBattery.test_emulate_energy_full_0c sVfdd}ttrdnd}tj||d"}|jtjjd|jsHt WdQRXdS)NcsRd}d}|j|s|j|r*ttjdn$|jdr>tjdS|f||SdS)Nz(/sys/class/power_supply/BAT0/energy_fullz(/sys/class/power_supply/BAT0/charge_fullr2z%/sys/class/power_supply/BAT0/capacitys88)rArrrrsrt)rxryrzZ energy_fullZ charge_full)r{r-r.r|5s  zHTestSensorsBattery.test_emulate_energy_full_not_avail..open_mockz builtins.openz__builtin__.open)r~X) rrr rrrZrhrirr)r]r|rrr-)r{r."test_emulate_energy_full_not_avail2s   z5TestSensorsBattery.test_emulate_energy_full_not_availc sDfdd}tjjtjd|d}tj|js6tWdQRXdS)Ncs|jdrdS|SdS)Nz"/sys/class/power_supply/AC0/onlineF)rA)rx)orig_path_existsr-r.path_exists_mockGs zGTestSensorsBattery.test_emulate_no_ac0_online..path_exists_mockzpsutil._pslinux.os.path.exists)r~) rrrr rrZrhrr)r]r{rr-)rzr.test_emulate_no_ac0_onlineEs   z-TestSensorsBattery.test_emulate_no_ac0_onlinec sTfdd}ttrdnd}tj||d }|jtjj|jsFt WdQRXdS)Ncs@|jds|jds|jdr,ttjdn|f||SdS)Nz!/sys/class/power_supply/AC/onlinez"/sys/class/power_supply/AC0/onlinez#/sys/class/power_supply/BAT0/statusr2)rArrr)rxryrz)r{r-r.r|Us    z;TestSensorsBattery.test_emulate_no_power..open_mockz builtins.openz__builtin__.open)r~) rrr rrrZrhrmrr)r]r|rrr-)r{r.test_emulate_no_powerSs   z(TestSensorsBattery.test_emulate_no_powerN)rrrrrrrjrnrprqrsrtrurvrwryr|r}r-r-r-r.rds rdc@s(eZdZejedddZddZdS)TestSensorsTemperatureszunreliable on TRAVIScsfdd}ttrdnd}tj||dN}tjdd6}|jtji|j sTt |j dt |d j WdQRXWdQRXdS) Ncs,|jdrttjdn|f||SdS)NZ_inputr2)rOSErrorrZEIO)rxryrz)r{r-r.r|is zATestSensorsTemperatures.test_emulate_eio_error..open_mockz builtins.openz__builtin__.open)r~T)rZignoringr)rrr rrrrrZsensors_temperaturesrrrrr)r]r|rrrr-)r{r.test_emulate_eio_errorgs   z.TestSensorsTemperatures.test_emulate_eio_errorcsfdd}ttrdnd}tj||djtjddgdNtjd d }|j|jd |j|jd |j|j d |j|j dWdQRXWdQRXdS)Ncs|jdrtjtdS|jdr0tjtdS|jdrDtjdS|jdrXtjdS|jd rltjd S|f||SdS) Nz/namerxz /temp1_labellabelz /temp1_inputs30000z /temp1_maxs40000z /temp1_crits50000)rrsrrrt)rxryrz)r{r-r.r|xs        z.open_mockz builtins.openz__builtin__.open)r~z glob.globz/sys/class/hwmon/hwmon0/temp1)rrxrrg>@gD@gI@) rrr rrZrrrrZhighZcritical)r]r|rZtempr-)r{r.test_emulate_dataws   z)TestSensorsTemperatures.test_emulate_dataN)rrrrrrrrr-r-r-r.r~dsr~c@seZdZddZdS)TestSensorsFanscsfdd}ttrdnd}tj||dNtjddgd2tjd d }|j|jd |j|jd WdQRXWdQRXdS) Ncs\|jdrtjtdS|jdr0tjtdS|jdrHtjtdS|f||SdS)Nz/namerxz /fan1_labelrz /fan1_inputZ2000)rrsrr)rxryrz)r{r-r.r|s   z4TestSensorsFans.test_emulate_data..open_mockz builtins.openz__builtin__.open)r~z glob.globz/sys/class/hwmon/hwmon2/fan1)rrxrri) rrr rrZZ sensors_fansrrr)r]r|rZfanr-)r{r.rs   z!TestSensorsFans.test_emulate_dataN)rrrrr-r-r-r.rsrc@seZdZddZeZddZejedddZ dd Z d d Z d d Z ddZ ddZddZddZddZddZeje dddZddZdd Zd!d"Zd#S)$ TestProcesscCs ttdS)N)rr)r]r-r-r.setUpszTestProcess.setUpcCstjdt}t|}|jttdddttj|j }t j d|j }|j dd}|j|jtdd |Dd d |j|jtd d |Dd d |j|jtd d |Dd d dS)Nzk import time with open("%s", "w") as f: time.sleep(10) cSs tjdS)NrU)rrr-r-r-r.sz3TestProcess.test_memory_full_info..z'%s' not in retg?F)ZgroupedcSsg|]}|j|jqSr-)Z private_dirtyZ private_clean)r3r0r-r-r.r5sz5TestProcess.test_memory_full_info..i)rccSsg|] }|jqSr-)pss)r3r0r-r-r.r5scSsg|] }|jqSr-)r)r3r0r-r-r.r5s)rurvrr rrrrZrRpidtimeZsleepZmemory_full_info memory_mapsr\ZussrErr)r]srcZsprocr_Zmemmapsr-r-r.test_memory_full_infos      z!TestProcess.test_memory_full_infozunreliable on PYPYc;CsRdd}ttd|j|jdWdQRXttd|j|jdWdQRXttd|j|jdWdQRXttd|j|jdWdQRXttd|j|jdWdQRXttd|j|jdWdQRXtrNttttd |j|jdWdQRXttttd |j|jdWdQRXdS) NcSs\tj}tjd}x:x4|jD](}|jtjjtkr:|Stj|kr Pq WqWtddS)Nrztimeout looking for test file) rZrRr open_filesrrabspathrr)r_Z giveup_atfiler-r-r. get_test_files   z7TestProcess.test_open_files_mode..get_test_filerr$rzr+zw+za+r0zx+)rrrmoderr)r]rr-r-r.test_open_files_modes(        z TestProcess.test_open_files_modecCstj}|j}tjt|jdt|tjdt t j dd"}|j}| sXt |j sbt WdQRXtjdt t jdd }|j|jg|j st WdQRXWdQRXdS)Nzlen(ret) != %izpsutil._pslinux.os.readlinkr2)r~)rZrRrrANamedTemporaryFilerrr rrrrrrZEINVALr)r]r_filesrr-r-r.test_open_files_file_gones  z%TestProcess.test_open_files_file_gonecCstj}|j}tjdt|jdt|tr6dnd}tj |t t j dd"}|j}| sdt |jsnt WdQRXWdQRXdS)Nzlen(ret) != %iz builtins.openz__builtin__.openr2)r~)rZrRrrArrrrr rrrrrr)r]r_rrrr-r-r.test_open_files_fd_gones   z#TestProcess.test_open_files_fd_gonec CsBtjdid*}|jtjjtjj|j s4t WdQRXdS)Nz)psutil._pslinux._psposix.get_terminal_map)r) r rrrZrrRrrbZterminalrr)r]rr-r-r.test_terminal_mockeds z TestProcess.test_terminal_mockedcCstj}tjtd}tjd|dd$}|j|jddg|j sFt WdQRXtjtd}tjd|dd&}|j|jdddg|j st WdQRXdS) Nzfoobarzpsutil._pslinux.openT)rr}rObarz foobarr2) rZrRrsrrr rrcmdlinerr)r]r_rrr-r-r.test_cmdline_mocked%s  zTestProcess.test_cmdline_mockedcCstj}tjtd}tjd|dd$}|j|jddg|j sFt WdQRXtjtd}tjd|dd&}|j|jdddg|j st WdQRXdS) Nzfoo bar zpsutil._pslinux.openT)rr}rOrz foo bar r2) rZrRrsrrr rrrrr)r]r_rrr-r-r.test_cmdline_spaces_mocked3s  z&TestProcess.test_cmdline_spaces_mockedc CsFtjddd.|jtjjd|jtjjdWdQRXdS)Nzpsutil._pslinux.os.readlinkz/home/foo (deleted))rz /home/foo)r rrrZrRexecwd)r]r-r-r.!test_readlink_path_deleted_mockedAs z-TestProcess.test_readlink_path_deleted_mockedcsfdd}ttrdnd}tj||d(}tjj}|jsBt|j |gWdQRXfdd}tj||d|j tj tjjWdQRXdS)Ncs4|jdtjr ttjdn|f||SdS)Nz /proc/%s/taskr2)rArrbrrr)rxryrz)r{r-r.r|Lsz2TestProcess.test_threads_mocked..open_mockz builtins.openz__builtin__.open)r~cs4|jdtjr ttjdn|f||SdS)Nz /proc/%s/taskr2)rArrbrrZEPERM)rxryrz)r{r-r.r|[s) rrr rrZrRrZrrrr AccessDenied)r]r|rrrr-)r{r.test_threads_mockedGs     zTestProcess.test_threads_mockedcCstjdttjdd}tjdtjddd`}tjj}|j sFt |j sPt |j |dtjddd|j tj tjjWdQRXWdQRXWdQRXdS) Nzpsutil._pslinux.readlinkr2)r~zpsutil.Process.cmdlinerzpsutil._pslinux.os.path.lexistsF)r)r rrrrrZrrRrrrrr ZombieProcess)r]r)r*rr-r-r.test_exe_mockedds     zTestProcess.test_exe_mockedcs|fdd}ttrdnd}tj||dH}tj}|jt}|jWdQRX|j |j j t j |j sntWdQRXdS)Ncs4|jdtjr ttjdn|f||SdS)Nz/proc/%s/smapsr2)rArrbrrr)rxryrz)r{r-r.r||sz.TestProcess.test_issue_1014..open_mockz builtins.openz__builtin__.open)r~)rrr rrZrRrrrr exceptionrrrr)r]r|rrr_errr-)r{r.test_issue_1014ys   zTestProcess.test_issue_1014z not supportedcCstjdttjddD}tj}|j|jtj }|j tj WdQRX|j sVt WdQRX|j|jj|j|j|jj|jdS)Nz"psutil._pslinux.cext.linux_prlimitr2)r~)r rrrZENOSYSrZrRrxrrZrlimitZ RLIMIT_NOFILErrrrr)r]rr_excr-r-r.test_rlimit_zombieszTestProcess.test_rlimit_zombiecCstjdttjdd@}tj}|j|jtj }|j WdQRX|j sRt WdQRX|j |jj|j|j |jj|jdS)Nzpsutil._pslinux.os.readlinkr2)r~)r rrrrrZrRrxrrrrrrrr)r]rr_rr-r-r.test_cwd_zombieszTestProcess.test_cwd_zombiec sddlm}fdd}ttr$dnd}tj||dtj}|j|j d|j|j tj |j|j d |j|j d |tj|j}|j|jd ||j|jd ||j|jd ||j|jd||j|jd WdQRXdS)Nr) CLOCK_TICKSc's|jdtjrxddddddddddddddddd ddddd ddddddddddddddddd g'}tjd j|jS|f||SdS) Nz /proc/%s/stat0z(cat)Z123456rQ)rArrbrsrtr;rw)rxryrz)r{r-r.r|sTz5TestProcess.test_stat_file_parsing..open_mockz builtins.openz__builtin__.open)r~catr7rrrarrN)rrrrr rrZrRrrxstatusZ STATUS_ZOMBIEppidZ create_timer>rusersystem children_userchildren_systemZcpu_num)r]rr|rr_Zcpur-)r{r.test_stat_file_parsings"  / z"TestProcess.test_stat_file_parsingc sfdd}ttrdnd}tj||dtj}|j|jjd|j|jj d|j|j d|j }|j|j d |j|j d |j|jd |j}|j|j d |j|j d |j|jd|j|jjttddWdQRXdS)Ncs:|jdtjr&tjtjdjS|f||SdS)Nz/proc/%s/statusa+ Uid: 1000 1001 1002 1003 Gid: 1004 1005 1006 1007 Threads: 66 Cpus_allowed: f Cpus_allowed_list: 0-7 voluntary_ctxt_switches: 12 nonvoluntary_ctxt_switches: 13)rArrbrsrtrurvrw)rxryrz)r{r-r.r|s z7TestProcess.test_status_file_parsing..open_mockz builtins.openz__builtin__.open)r~rb Biiiiiirr-)rrr rrZrRrnum_ctx_switches voluntary involuntary num_threadsuidsrealZ effectiveZsavedgids_proc_get_eligible_cpuslistrange)r]r|rr_rrr-)r{r.test_status_file_parsings"  z$TestProcess.test_status_file_parsingN)rrrrZtearDownrrrr rrrrrrrrrrr rrrrr-r-r-r.rs"$ Brc@sreZdZdZeddZddZddZdd Zd d Z d d Z ddZ ddZ e ddZddZddZdS)TestProcessAgainstStatusa /proc/pid/stat and /proc/pid/status have many values in common. Whenever possible, psutil uses /proc/pid/stat (it's faster). For all those cases we check that the value found in /proc/pid/stat (by psutil) matches the one found in /proc/pid/status. cCstj|_dS)N)rZrRproc)clsr-r-r. setUpClasssz#TestProcessAgainstStatus.setUpClasscCs|tjjd|jj^}xJ|D]B}|j}|j|r|jdd}yt|St k r\|SXqWt d|WdQRXdS)Nz/proc/%s/status rz can't find %r) rZ _psplatform open_textrrrRrA partitionrDrE)r]Z linestartrrHrr-r-r.read_status_files   z)TestProcessAgainstStatus.read_status_filecCs |jd}|j|jj|dS)NzName:)rrrrx)r]rr-r-r. test_name!s z"TestProcessAgainstStatus.test_namecCsH|jd}||jdd|jd}|jdd}|j|jj|dS)NzState:(r7)rQr)rfindrfindrgrrr)r]rr-r-r. test_status%s  z$TestProcessAgainstStatus.test_statuscCs |jd}|j|jj|dS)NzPPid:)rrrr)r]rr-r-r. test_ppid+s z"TestProcessAgainstStatus.test_ppidcCs |jd}|j|jj|dS)NzThreads:)rrrr)r]rr-r-r.test_num_threads/s z)TestProcessAgainstStatus.test_num_threadscCs:|jd}ttt|jdd}|j|jj|dS)NzUid:r7r)rrVrWrDr@rrr)r]rr-r-r. test_uids3s z"TestProcessAgainstStatus.test_uidscCs:|jd}ttt|jdd}|j|jj|dS)NzGid:r7r)rrVrWrDr@rrr)r]rr-r-r. test_gids8s z"TestProcessAgainstStatus.test_gidscCs@|jd}|j|jjj||jd}|j|jjj|dS)Nzvoluntary_ctxt_switches:znonvoluntary_ctxt_switches:)rrrrrr)r]rr-r-r.test_num_ctx_switches=s  z.TestProcessAgainstStatus.test_num_ctx_switchescCsN|jd}dt|krJtt|jd\}}|j|jjtt ||ddS)NzCpus_allowed_list:rr7) rrrWrDr@rrZ cpu_affinityrr)r]rZmin_Zmax_r-r-r.test_cpu_affinityDs   z*TestProcessAgainstStatus.test_cpu_affinityc CsT|jd}tjd}|jjjWdQRXdt|krF|j sPtn |jsPtdS)NzCpus_allowed_list:zpsutil._pslinux.per_cpu_timesr) rr rrrrrrr)r]rrr-r-r.test_cpu_affinity_eligible_cpusKs    z8TestProcessAgainstStatus.test_cpu_affinity_eligible_cpusN)rrr__doc__ classmethodrrrrrrrrrrrrr-r-r-r.rs  rc@s,eZdZddZddZddZddZd S) TestUtilsc Cs*tjjt}|j|jdWdQRXdS)NZrt)rZrr__file__rr)r]rr-r-r.test_open_text]szTestUtils.test_open_textc Cs*tjjt}|j|jdWdQRXdS)Nr)rZrrrrr)r]rr-r-r.test_open_binaryaszTestUtils.test_open_binaryc Cs<tjddd$}|jtjjdd|js.tWdQRXdS)Nz os.readlinkz foo (deleted))rrrO)r rrrZrreadlinkrr)r]rr-r-r. test_readlinkeszTestUtils.test_readlinkc Cs|tjjt}t|d}|jdWdQRX|jtjj tddd|jtjj tddd|jtjj tdd d d dS) NZwtzfoo F)ZbinaryrOTsfooz??r)Zfallback) rrrrrrCrrZrr)r]Zfnamerr-r-r.test_catjs  zTestUtils.test_catN)rrrrrrrr-r-r-r.rZsr__main__)KrZ __future__rrBr$rrrsrr rrFr!r)rArurrrZrZpsutil._compatrrZ psutil.testsrrrr r r r r rrrrrrrrrrrrrrdirnamerZHEREr(Z SIOCGIFCONFr9r2r/r=rMrPrTrXrZTestCaserYrrrrrr=rdr~rrrrrr-r-r-r.s                             k T  t  .  7 -  Y R  PK!Z)*)*#__pycache__/test_osx.cpython-36.pycnu[3 JZ%@s<dZddlZddlZddlZddlZddlmZddlmZddlmZddlm Z ddlm Z ddlm Z dd lm Z dd lm Z dd lmZdd lmZerejd ndZddZddZddZeje dGdddejZeje dGdddejZeje dGdddejZedkr8e edS)zOSX specific tests.N)OSX)create_zombie_proc)get_test_subprocess) HAS_BATTERY)MEMORY_TOLERANCE) reap_children)retry_before_failing)run_test_module_by_name)sh)unittest SC_PAGE_SIZEc Cs6t|}|jd}yt|Stk r0|SXdS)zmExpects a sysctl command with an argument and parse the result returning only the value of interest. N)r splitint ValueError)cmdlineoutresultr /usr/lib64/python3.6/test_osx.pysysctls  rcCsHtd}x$|jdD]}||krPqWtdttjd|jdtS)z)Wrapper around 'vm_stat' cmdline utility.vm_stat zline not foundz\d+r)r rrrresearchgroupPAGESIZE)Zfieldrlinerrrr(s rc Csddi}|}d }x@|r&|d d js6|d d dkrP||d 7}|d d}qWt|}|j}xD|jD]\}}||krlPqlW|dkr|d}|j}n td||d d i}x0t|d dD]\}}d |d d>||<qWt|||S)NZ customaryBKMGTPEZYrr .kzcan't interpret %r ) rrr r!r"r#r$r%r&)isdigitfloatstripitemsupperr enumerater) sZSYMBOLSZinitnumZletternameZssetprefixirrr human2bytes4s&&    r6zOSX onlyc@s,eZdZeddZeddZddZdS) TestProcesscCstj|_dS)N)rpid)clsrrr setUpClassQszTestProcess.setUpClasscCs tdS)N)r)r9rrr tearDownClassUszTestProcess.tearDownClasscCstd|j}|jddj}|jdd }|jdd }tj|jj}|j|t j dt j ||j|t j dt j |dS) Nzps -o lstart -p %sZSTARTEDr' r z%H:%M:%Sz%Y) r r8replacer-rpsutilProcess create_time assertEqualtimeZstrftimeZ localtime)selfoutputZstart_psZhhmmssZyearZ start_psutilrrrtest_process_create_timeYsz$TestProcess.test_process_create_timeN)__name__ __module__ __qualname__ classmethodr:r;rHrrrrr7Ns  r7c@seZdZeddZeddZddZddZd d Zd d Z d dZ ddZ ddZ ddZ ddZddZddZddZddZdd Zd!S)"TestZombieProcessAPIscCst}tj||_dS)N)rrArBp)r9Zzpidrrrr:jsz TestZombieProcessAPIs.setUpClasscCstdddS)NT) recursive)r)r9rrrr;osz#TestZombieProcessAPIs.tearDownClasscCsJ|j|jjtj|jj|jj|jj|jj|jj dS)N) rDrNZstatusrAZ STATUS_ZOMBIEZppidZuidsZgidsZterminalrC)rFrrrtest_pidtask_infoss     z'TestZombieProcessAPIs.test_pidtask_infocCs|jtj|jjdS)N) assertRaisesrA ZombieProcessrNZexe)rFrrrtest_exe{szTestZombieProcessAPIs.test_execCs|jtj|jjdS)N)rQrArRrNr)rFrrr test_cmdline~sz"TestZombieProcessAPIs.test_cmdlinecCs|jtj|jjdS)N)rQrArRrNenviron)rFrrr test_environsz"TestZombieProcessAPIs.test_environcCs|jtj|jjdS)N)rQrArRrNcwd)rFrrrtest_cwdszTestZombieProcessAPIs.test_cwdcCs|jtj|jjdS)N)rQrArRrNZmemory_full_info)rFrrrtest_memory_full_infosz+TestZombieProcessAPIs.test_memory_full_infocCs|jtj|jjdS)N)rQrArRrNZ cpu_times)rFrrrtest_cpu_timessz$TestZombieProcessAPIs.test_cpu_timescCs|jtj|jjdS)N)rQrArRrNZnum_ctx_switches)rFrrrtest_num_ctx_switchessz+TestZombieProcessAPIs.test_num_ctx_switchescCs|jtj|jjdS)N)rQrArRrNZ num_threads)rFrrrtest_num_threadssz&TestZombieProcessAPIs.test_num_threadscCs|jtj|jjdS)N)rQrArRrNZ open_files)rFrrrtest_open_filessz%TestZombieProcessAPIs.test_open_filescCs|jtj|jjdS)N)rQrArRrNZ connections)rFrrrtest_connectionssz&TestZombieProcessAPIs.test_connectionscCs|jtj|jjdS)N)rQrArRrNZnum_fds)rFrrr test_num_fdssz"TestZombieProcessAPIs.test_num_fdscCs|jtjtjf|jjdS)N)rQrArRZ AccessDeniedrNZthreads)rFrrr test_threadssz"TestZombieProcessAPIs.test_threadscCs|jtj|jjdS)N)rQrArRrNZ memory_maps)rFrrrtest_memory_mapssz&TestZombieProcessAPIs.test_memory_mapsN)rIrJrKrLr:r;rPrSrTrVrXrYrZr[r\r]r^r_r`rarrrrrMgs   rMc@seZdZddZddZddZddZd d Zed d Z ed dZ eddZ eddZ eddZ eddZeddZddZeje dddZdS)TestSystemAPIscCsdd}xtjddD]}tj|j}||j\}}}}|j|j||j|j|t|j|d krx|j d|j|t|j |d kr|j d|j |qWdS) NcSstd|j}|jd}|jd|jd}|jdd\}}}}|dkrRd}t|d}t|d}t|d}||||fS)Nz df -k "%s"rrZnoner'i)r r-rpopr)pathrlinesrdevtotalusedfreerrrdfs      z%TestSystemAPIs.test_disks..dfF)allr*izpsutil=%s, df=%si(ii(i) rAZdisk_partitionsZ disk_usageZ mountpointrDZdevicerhabsrjZfailri)rFrkpartZusagergrhrirjrrr test_diskss  zTestSystemAPIs.test_diskscCs td}|j|tjdddS)Nzsysctl hw.logicalcpuT)logical)rrDrA cpu_count)rFr2rrrtest_cpu_count_logicalsz%TestSystemAPIs.test_cpu_count_logicalcCs td}|j|tjdddS)Nzsysctl hw.physicalcpuF)rp)rrDrArq)rFr2rrrtest_cpu_count_physicalsz&TestSystemAPIs.test_cpu_count_physicalcCsZtj}|j|jddtd|j|jddtd|j|jddtddS)Nizsysctl hw.cpufrequencyzsysctl hw.cpufrequency_minzsysctl hw.cpufrequency_max)rAZcpu_freqrDZcurrentrminmax)rFZfreqrrr test_cpu_freqszTestSystemAPIs.test_cpu_freqcCstd}|j|tjjdS)Nzsysctl hw.memsize)rrDrAvirtual_memoryrh)rFZsysctl_hwphymemrrrtest_vmem_totalszTestSystemAPIs.test_vmem_totalcCs&td}tjj}|j||tddS)Nrj)delta)rrArwrjassertAlmostEqualr)rF vmstat_val psutil_valrrrtest_vmem_frees zTestSystemAPIs.test_vmem_freecCs.tdtd}tjj}|j||tddS)Ninactiverj)ry)rrArwZ availablerzr)rFr{r|rrrtest_vmem_availables z"TestSystemAPIs.test_vmem_availablecCs&td}tjj}|j||tddS)Nactive)ry)rrArwrrzr)rFr{r|rrrtest_vmem_actives zTestSystemAPIs.test_vmem_activecCs&td}tjj}|j||tddS)Nr~)ry)rrArwr~rzr)rFr{r|rrrtest_vmem_inactives z!TestSystemAPIs.test_vmem_inactivecCs&td}tjj}|j||tddS)Nwired)ry)rrArwrrzr)rFr{r|rrrtest_vmem_wireds zTestSystemAPIs.test_vmem_wiredcCs"td}tjj}|j||dS)NZPageins)rrA swap_memoryZsinrD)rFr{r|rrrtest_swapmem_sins zTestSystemAPIs.test_swapmem_sincCs"td}tjj}|j||dS)NZPageout)rrArZsoutrD)rFr{r|rrrtest_swapmem_souts z TestSystemAPIs.test_swapmem_soutcCsxxrtjjD]b\}}ytd|}Wntk r:YqX|j|jd|k|d|j|jtt j d|dqWdS)Nz ifconfig %sZRUNNING)msgz mtu (\d+)r) rAZ net_if_statsr.r RuntimeErrorrDZisupZmturrfindall)rFr3Zstatsrrrrtest_net_if_statssz TestSystemAPIs.test_net_if_statsz no batterycCs`td}tjd|jd}tjd|jd}|dk}tj}|j|j||j|jt |dS)Nz pmset -g battz(\d+)%r zNow drawing from '([^']+)'zAC Power) r rrrrAZsensors_batteryrD power_pluggedpercentr)rFrrZ drawing_fromrZ psutil_resultrrrtest_sensors_battery"sz#TestSystemAPIs.test_sensors_batteryN)rIrJrKrorrrsrvrxrr}rrrrrrrr skipIfrrrrrrrbs  rb__main__)__doc__osrrErArZ psutil.testsrrrrrrr r r sysconfrrrr6rZTestCaser7rMrbrI__file__rrrrs6              <  PK!k'++'__pycache__/test_unicode.cpython-36.pycnu[3 JZ[2@sdZddlZddlZddlZddlmZddlmZddlmZddlm Z ddlm Z ddlm Z dd l m Z dd l mZdd lmZdd lmZdd lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddlm$Z$ddlm%Z%dd lm&Z&ddlZddlZd!d"Zd#d$Z'e re"j(d%d&j)d%d'Z*ne"d(Z*Gd)d*d*e+Z,e%j-e oe$d+e%j-ed,e%j-e'e# d-Gd.d/d/e,e%j.Z/e%j-e o*e$d+e%j-e'e* d0Gd1d2d2e,e%j.Z0e%j-e d3Gd4d5d5e%j.Z1Gd6d7d7e%j.Z2e3d8kree4dS)9a Notes about unicode handling in psutil ====================================== In psutil these are the APIs returning or dealing with a string ('not tested' means they are not tested to deal with non-ASCII strings): * Process.cmdline() * Process.connections('unix') * Process.cwd() * Process.environ() * Process.exe() * Process.memory_maps() * Process.name() * Process.open_files() * Process.username() (not tested) * disk_io_counters() (not tested) * disk_partitions() (not tested) * disk_usage(str) * net_connections('unix') * net_if_addrs() (not tested) * net_if_stats() (not tested) * net_io_counters() (not tested) * sensors_fans() (not tested) * sensors_temperatures() (not tested) * users() (not tested) * WindowsService.binpath() (not tested) * WindowsService.description() (not tested) * WindowsService.display_name() (not tested) * WindowsService.name() (not tested) * WindowsService.status() (not tested) * WindowsService.username() (not tested) In here we create a unicode path with a funky non-ASCII name and (where possible) make psutil return it back (e.g. on name(), exe(), open_files(), etc.) and make sure that: * psutil never crashes with UnicodeDecodeError * the returned path matches For a detailed explanation of how psutil handles unicode see: - https://github.com/giampaolo/psutil/issues/1040 - http://psutil.readthedocs.io/#unicode N)closing)BSD)OPENBSD)OSX)POSIX)WINDOWS)PY3)u)APPVEYOR)ASCII_FS)bind_unix_socket)chdir)copyload_shared_lib) create_exe)get_test_subprocess)HAS_CONNECTIONS_UNIX) HAS_ENVIRON)HAS_MEMORY_MAPS)mock) reap_children)run_test_module_by_name) safe_mkdir) safe_rmpath)skip_on_access_denied)TESTFILE_PREFIX)TESTFN)TESTFN_UNICODE)TRAVIS)unittest)unix_socket_pathc Cs8tr,yt|Stk r(tjYq4Xnt|SdS)N)r _safe_rmpathZ WindowsError traceback print_exc)pathr$$/usr/lib64/python3.6/test_unicode.pyr\s  rcCsTtrdSz>y t|t|t|gdWntk r>dSXdSWdtXdS)z`Return True if both the fs and the subprocess module can deal with a unicode file name. T)cmdFN)rrrrUnicodeEncodeErrorr)namer$r$r%subprocess_supports_unicodepsr)utf8sfsurrogateescapeufÀ€c@seZdZdZeddZeddZddZdd Zd d Z d d Z ddZ ddZ ddZ eje dddZeje deje deddZddZeje deje dddZdS) _BaseFSAPIsTestsNcCst|jt|jdS)N)r funky_namer)clsr$r$r% setUpClasss z_BaseFSAPIsTests.setUpClasscCstt|jdS)N)rrr-)r.r$r$r% tearDownClasssz_BaseFSAPIsTests.tearDownClasscCs tdS)N)r)selfr$r$r%tearDownsz_BaseFSAPIsTests.tearDowncCs tddS)Nzmust be implemented in subclass)NotImplementedError)r1r$r$r%expect_exact_path_matchsz(_BaseFSAPIsTests.expect_exact_path_matchcCsHt|jgd}tj|j}|j}|j|t|jrD|j ||jdS)N)r&) rr-psutilProcesspidexeassertIsInstancestrr4 assertEqual)r1subppr8r$r$r% test_proc_exes   z_BaseFSAPIsTests.test_proc_exec Cst|jgd}trRtjdtjtjd }tj |j j }|j sFt WdQRXntj |j j }|j|t|jr|j|tjj|jdS)N)r&z psutil._psplatform.cext.proc_exe) side_effect)rr-rrpatchr5 AccessDeniedosgetpidr6r7r(calledAssertionErrorr9r:r4r;r#basename)r1r<mr(r$r$r%test_proc_names z_BaseFSAPIsTests.test_proc_namecCsXt|jgd}tj|j}|j}x|D]}|j|tq(W|jrT|j ||jgdS)N)r&) rr-r5r6r7cmdliner9r:r4r;)r1r<r=rIpartr$r$r%test_proc_cmdlines  z"_BaseFSAPIsTests.test_proc_cmdlinec Csj|jd}|jt|t|t|tj}|j}WdQRX|j|jt |j rf|j ||dS)N2) r- addCleanuprrr r5r6cwdr9r:r4r;)r1dnamer=rNr$r$r% test_proc_cwds   z_BaseFSAPIsTests.test_proc_cwdc Cstj}t|j}t|jdt|j}WdQRX||jj}|j|t t rf| rf|j dS|j r|j tjj|tjj|jdS)Nrbzopen_files on BSD is broken)r5r6setZ open_filesopenr-popr#r9r:rZskipTestr4r;rBnormcase)r1r=startnewr#r$r$r%test_proc_open_filess    z%_BaseFSAPIsTests.test_proc_open_filesz POSIX onlycCstjj|j}t|d}y t|}Wn&tk rLtr>n tj dYnXt |8t j j dd}|j|jtts|j|j|WdQRXWdQRXdS)N)suffixz not supportedunixr)rBr#rFr-rr r'rrSkipTestrr5r6Z connectionsr9laddrr:rr;)r1rYr(sockconnr$r$r%test_proc_connectionss   z&_BaseFSAPIsTests.test_proc_connectionszcan't list UNIX socketscCsdd}tjj|j}t|d}y t|}Wn&tk rTtrFn tj dYnXt |:t j dd}t s||}|j|jt|j|j|WdQRXWdQRXdS)NcSs2x$|D]}tjj|jjtr|SqWtddS)Nzconnection not found)rBr#rFr\ startswithr ValueError)consr^r$r$r% find_socks z8_BaseFSAPIsTests.test_net_connections..find_sock)rYz not supportedrZ)Zkind)rBr#rFr-rr r'rrr[rr5Znet_connectionsrr9r\r:r;)r1rcrYr(r]rbr^r$r$r%test_net_connectionss    z%_BaseFSAPIsTests.test_net_connectionscCs,|jd}|jt|t|tj|dS)NrL)r-rMrrr5Z disk_usage)r1rOr$r$r%test_disk_usage s  z _BaseFSAPIsTests.test_disk_usagez not supportedz&ctypes does not support unicode on PY2c svt|jd`}ddfddtjjD}dd|D}|j||x|D]}|j|tqTWWdQRXdS)N)Z dst_prefixcSstjjtjj|S)N)rBr#realpathrU)r=r$r$r%normpathsz3_BaseFSAPIsTests.test_memory_maps..normpathcsg|]}|jqSr$)r#).0x)rgr$r% sz5_BaseFSAPIsTests.test_memory_maps..cSsg|]}t|kr|qSr$)r)rhrir$r$r%rjs)rr-r5r6Z memory_mapsZassertInr9r:)r1Z funky_pathZlibpathsr#r$)rgr%test_memory_mapss  z!_BaseFSAPIsTests.test_memory_maps)__name__ __module__ __qualname__r- classmethodr/r0r2r4r>rHrKrPrXrskipIfrr_rrrdrerrrkr$r$r$r%r,s"       r,zunreliable on TRAVISzASCII fsz"subprocess can't deal with unicodec@s eZdZdZeZeddZdS) TestFSAPIsz1Test FS APIs with a funky, valid, UTF8 path name.c CsNtrdSt|jtrdntd}tjtjd|jtj |kSQRXdS)NT.ignore) r isinstancer-r:r warningscatch_warnings simplefilterrBlistdir)r.herer$r$r%r4(s   z"TestFSAPIs.expect_exact_path_matchN)rlrmrn__doc__rr-ror4r$r$r$r%rq srqz*subprocess can't deal with invalid unicodec@s eZdZdZeZeddZdS)TestFSAPIsWithInvalidPathz-Test FS APIs with a funky, invalid path name.cCsdS)NTr$)r.r$r$r%r4<sz1TestFSAPIsWithInvalidPath.expect_exact_path_matchN)rlrmrnrz INVALID_NAMEr-ror4r$r$r$r%r{5sr{z WINDOWS onlyc@seZdZddZdS)TestWinProcessNamec CsFtjdtjtjd$}|jtjjt |j s8t WdQRXdS)Nz psutil._psplatform.cext.proc_exe)r?) rr@r5rArBrCr9r6r(r:rDrE)r1rGr$r$r%test_name_typeEsz!TestWinProcessName.test_name_typeN)rlrmrnr~r$r$r$r%r}Bsr}c@s.eZdZdZddZeje dddZdS) TestNonFSAPISz&Unicode tests for non fs-related APIs.cCs tdS)N)r)r1r$r$r%r2WszTestNonFSAPIS.tearDownz not supportedcCs~tjj}trtnd}||d<t|d}tj|j}|j}x,|j D] \}}|j |t |j |t qFW|j |d|dS)NèZ FUNNY_ARG)env) rBenvironcopyrrrr5r6r7itemsr9r:r;)r1rZ funky_strZsprocr=kvr$r$r%test_proc_environZs     zTestNonFSAPIS.test_proc_environN) rlrmrnrzr2rrprrr$r$r$r%rTsr__main__)5rzrBr!ru contextlibrr5rrrrrZpsutil._compatrr Z psutil.testsr r r r rrrrrrrrrrrr rrrrrrrr)encodedecoder|objectr,rpZTestCaserqr{r}rrl__file__r$r$r$r%4sr                                     PK!,UU,__pycache__/test_memory_leaks.cpython-36.pycnu[3 JZ=G@s<dZddlmZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl m Z ddl m Z ddl mZddl mZddl mZdd l mZdd lmZdd lmZdd lmZdd lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddlm$Z$ddlm%Z%ddlm&Z&ddlm'Z'ddlm(Z(dZ)d Z*d!Z+e'rd"nd#Z,e j-j.Z.e j/Z0e'rd"nd#Z,d$d%Z1d&d'Z2Gd(d)d)e(j3Z4Gd*d+d+e4Z5Gd,d-d-e5Z6Gd.d/d/e4Z7e8d0kr8e#e9dS)1a) Tests for detecting function memory leaks (typically the ones implemented in C). It does so by calling a function many times and checking whether process memory usage keeps increasing between calls or over time. Note that this may produce false positives (especially on Windows for some reason). )print_functionN)LINUX)OPENBSD)OSX)POSIX)SUNOS)WINDOWS)xrange)create_sockets)get_test_subprocess)HAS_CPU_AFFINITY) HAS_CPU_FREQ) HAS_ENVIRON) HAS_IONICE)HAS_MEMORY_MAPS)HAS_PROC_CPU_NUM)HAS_PROC_IO_COUNTERS) HAS_RLIMIT)HAS_SENSORS_BATTERY)HAS_SENSORS_FANS)HAS_SENSORS_TEMPERATURES) reap_children)run_test_module_by_name) safe_rmpath)skip_on_access_denied)TESTFN)TRAVIS)unittestiiTFcCstjto tdS)Nz worthless on LINUX (pure python))rskipIfrSKIP_PYTHON_IMPLr!r!)/usr/lib64/python3.6/test_memory_leaks.py skip_if_linuxFs r#cCstd }i}x(t|D]\}}d |d d >||<qWx8t|D],}|||kr>> bytes2human(10000) '9.8K' >>> bytes2human(100001221) '95.4M' KMGTPEZY z%.2f%sz%sB)r$r%r&r'r(r)r*r+) enumeratereversedfloat)nZsymbolsprefixisvaluer!r!r" bytes2humanKs r6c@sLeZdZdZeZeZeZ ddZ ddZ ddZ e dd Ze d d Zd S) TestMemLeakzBase framework class which calls a function many times and produces a failure if process memory usage keeps increasing between calls or over time. cCs tjdS)N)gccollect)selfr!r!r"setUpgszTestMemLeak.setUpcs~fdd}jddp$j}jddp6jjddpHj}x"tdD]}jfqTWjtjgjt j djt j g|j }|j } | |} | |krzd } tj|} x,tj| krjf| d7} qW~ tjj } | | }| | krzt| |}td |tjd d }|d 7}|t| t|| |f}j|dS)zTest a callable.cs2x"tD]}jfq W~tjdS)N)r _callr8r9)x)argsfunkwargsloopsr:r!r"call_many_timeslsz,TestMemLeak.execute..call_many_times tolerance_NZloops_Z retry_for_r-r,rzexta proc mem: %s)filez0+%s after %s calls, +%s after another %s calls, z+%s extra proc mem)pop tolerancerA retry_forranger<Z assertEqualr8Zgarbage threadingZ active_countthisprocchildren_get_memtimer9r6printsysstderrZfail)r:r?r>r@rBrFrGr=Zmem1Zmem2Zdiff1ZncallsZstop_atZmem3Zdiff2Zextra_proc_memmsgr!)r>r?r@rAr:r"executejsB     zTestMemLeak.executecs"fdd}j|dS)zRConvenience function which tests a callable raising an exception. csjfdS)N)Z assertRaisesr!)r>excr?r@r:r!r"callsz'TestMemLeak.execute_w_exc..callN)rR)r:rSr?r>r@rTr!)r>rSr?r@r:r" execute_w_excszTestMemLeak.execute_w_exccCs$ts ts trtjjStjjSdS)N)rrrrJmemory_full_infoZuss memory_infoZrssr!r!r!r"rLs  zTestMemLeak._get_memcOs|||dS)Nr!)r?r>r@r!r!r"r<szTestMemLeak._callN)__name__ __module__ __qualname____doc__MEMORY_TOLERANCErFLOOPSrA RETRY_FORrGr;rRrU staticmethodrLr<r!r!r!r"r7^s; r7c@seZdZdZeZddZeddZeddZ edd Z ed d Z e j e d ed dZe j e d eddZeddZddZddZe j e dddZe j e dddZe j e deddZe j eddd Zed!d"Zeeed#d$d%Ze j e d&d'd(Ze j e d ed)d*Z ed+d,Z!eeed#d-d.Z"ed/d0Z#ee j e$ dd1d2Z%ed3d4Z&ed5d6Z'e j e d ed7d8Z(e j eoe)d9d:d;Z*edd?Z-e j e, dd@dAZ.edBdCZ/e j e0dDe j e1 dedEdFZ2e j e3 dGe j e4 ddHdIZ5e j e3 dGe j e4 ddJdKZ6ee j edLdMdNZ7e j e8 ddOdPZ9e j e d&dQdRZ:dSS)TTestProcessObjectLeaksz$Test leaks of Process class methods.cCsNtd}x@ttjD]2}|jdr$q||kr.q|jt|d||dqWdS)Npidas_dictrK cpu_affinity cpu_percentionice is_runningkillmemory_info_exmemory_percentniceoneshotparentrlimit send_signalsuspend terminatewait_test_)rQ)rarbrKrcrdrerfrgrhrirjrkrlrmrnrorprq)setdirpsutilProcess startswith assertTruehasattr)r:skipnamer!r!r" test_coverages z$TestProcessObjectLeaks.test_coveragecCs|j|jjdS)N)rRprocr|)r:r!r!r" test_namesz TestProcessObjectLeaks.test_namecCs|j|jjdS)N)rRr~Zcmdline)r:r!r!r" test_cmdlinesz#TestProcessObjectLeaks.test_cmdlinecCs|j|jjdS)N)rRr~Zexe)r:r!r!r"test_exeszTestProcessObjectLeaks.test_execCs|j|jjdS)N)rRr~Zppid)r:r!r!r" test_ppidsz TestProcessObjectLeaks.test_ppidz POSIX onlycCs|j|jjdS)N)rRr~Zuids)r:r!r!r" test_uidssz TestProcessObjectLeaks.test_uidscCs|j|jjdS)N)rRr~Zgids)r:r!r!r" test_gidssz TestProcessObjectLeaks.test_gidscCs|j|jjdS)N)rRr~Zstatus)r:r!r!r" test_statussz"TestProcessObjectLeaks.test_statuscCs|j|jjdS)N)rRr~rj)r:r!r!r" test_nice_getsz$TestProcessObjectLeaks.test_nice_getcCstj}|j|jj|dS)N)rJrjrRr~)r:Znicenessr!r!r" test_nice_setsz$TestProcessObjectLeaks.test_nice_setz not supportedcCs|j|jjdS)N)rRr~re)r:r!r!r"test_ionice_getsz&TestProcessObjectLeaks.test_ionice_getcCsVtrtj}|j|jj|n4|j|jjtjtjt j t j dd}|j t|dS)Nr,r)rrJrerRr~rvZIOPRIO_CLASS_NONE functoolspartialcextZproc_ioprio_setosgetpidrUOSError)r:r5r?r!r!r"test_ionice_sets z&TestProcessObjectLeaks.test_ionice_setcCs|j|jjdS)N)rRr~Z io_counters)r:r!r!r"test_io_counterssz'TestProcessObjectLeaks.test_io_counterszworthless on POSIXcCs|j|jjdS)N)rRr~Zusername)r:r!r!r" test_username sz$TestProcessObjectLeaks.test_usernamecCs|j|jjdS)N)rRr~Z create_time)r:r!r!r"test_create_timesz'TestProcessObjectLeaks.test_create_time)Zonly_ifcCs|j|jjdS)N)rRr~Z num_threads)r:r!r!r"test_num_threadssz'TestProcessObjectLeaks.test_num_threadsz WINDOWS onlycCs|j|jjdS)N)rRr~Z num_handles)r:r!r!r"test_num_handlessz'TestProcessObjectLeaks.test_num_handlescCs|j|jjdS)N)rRr~Znum_fds)r:r!r!r" test_num_fdssz#TestProcessObjectLeaks.test_num_fdscCs|j|jjdS)N)rRr~Znum_ctx_switches)r:r!r!r"test_num_ctx_switches!sz,TestProcessObjectLeaks.test_num_ctx_switchescCs|j|jjdS)N)rRr~Zthreads)r:r!r!r" test_threads%sz#TestProcessObjectLeaks.test_threadscCs|j|jjdS)N)rRr~ cpu_times)r:r!r!r"test_cpu_times*sz%TestProcessObjectLeaks.test_cpu_timescCs|j|jjdS)N)rRr~Zcpu_num)r:r!r!r" test_cpu_num.sz#TestProcessObjectLeaks.test_cpu_numcCs|j|jjdS)N)rRr~rW)r:r!r!r"test_memory_info3sz'TestProcessObjectLeaks.test_memory_infocCs|j|jjdS)N)rRr~rV)r:r!r!r"test_memory_full_info7sz,TestProcessObjectLeaks.test_memory_full_infocCs|j|jjdS)N)rRr~Zterminal)r:r!r!r" test_terminal;sz$TestProcessObjectLeaks.test_terminalz worthless on POSIX (pure python)cCs|j|jjdS)N)rRr~resume)r:r!r!r" test_resume@sz"TestProcessObjectLeaks.test_resumecCs|j|jjdS)N)rRr~cwd)r:r!r!r"test_cwdEszTestProcessObjectLeaks.test_cwdcCs|j|jjdS)N)rRr~rc)r:r!r!r"test_cpu_affinity_getIsz,TestProcessObjectLeaks.test_cpu_affinity_getcCs4tj}|j|jj|ts0|jt|jjdgdS)Nr,r)rJrcrRr~rrU ValueError)r:Zaffinityr!r!r"test_cpu_affinity_setMsz,TestProcessObjectLeaks.test_cpu_affinity_setc Cs0ttttd|j|jjWdQRXdS)Nw)rropenrRr~Z open_files)r:r!r!r"test_open_filesTs z&TestProcessObjectLeaks.test_open_filesztoo slow on OSXcCs|j|jjdS)N)rRr~Z memory_maps)r:r!r!r"test_memory_maps[sz'TestProcessObjectLeaks.test_memory_mapsz LINUX onlycCs|j|jjtjdS)N)rRr~rmrv RLIMIT_NOFILE)r:r!r!r"test_rlimit_getasz&TestProcessObjectLeaks.test_rlimit_getcCs6tjtj}|j|jjtj||jt|jjddS)Nr,r)rJrmrvrrRr~rUr)r:limitr!r!r"test_rlimit_setfs z&TestProcessObjectLeaks.test_rlimit_setzworthless on WINDOWSc Cs2t"trdnd}|j|jj|WdQRXdS)NZinetall)r rrRr~Z connections)r:Zkindr!r!r"test_connectionsms z'TestProcessObjectLeaks.test_connectionscCs|j|jjdS)N)rRr~environ)r:r!r!r" test_environysz#TestProcessObjectLeaks.test_environcCs|jtjtjdS)N)rRr proc_inforr)r:r!r!r"test_proc_info}sz%TestProcessObjectLeaks.test_proc_infoN);rXrYrZr[rJr~r}r#rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr rrr rrrrrrrrrrrrrrr!r!r!r"r`sh            r`cspeZdZdZefddZefddZddZerhdd Z d d Z d d Z ddZ ddZ ddZZS)TestTerminatedProcessLeakszRepeat the tests above looking for leaks occurring when dealing with terminated processes raising NoSuchProcess exception. The C functions are still invoked but will follow different code paths. We'll check those code paths. cs:tt|jt}tj|j|_|jj|jj dS)N) superr setUpClassr rvrwrar~rgrq)clsp) __class__r!r"rs  z%TestTerminatedProcessLeaks.setUpClasscstt|jtdS)N)rr tearDownClassr)r)rr!r"rsz(TestTerminatedProcessLeaks.tearDownClassc Os*y|||Wntjk r$YnXdS)N)rvZ NoSuchProcess)r:r?r>r@r!r!r"r<sz TestTerminatedProcessLeaks._callcCs|j|jjdS)N)rRr~rg)r:r!r!r" test_killsz$TestTerminatedProcessLeaks.test_killcCs|j|jjdS)N)rRr~rp)r:r!r!r"test_terminatesz)TestTerminatedProcessLeaks.test_terminatecCs|j|jjdS)N)rRr~ro)r:r!r!r" test_suspendsz'TestTerminatedProcessLeaks.test_suspendcCs|j|jjdS)N)rRr~r)r:r!r!r"rsz&TestTerminatedProcessLeaks.test_resumecCs|j|jjdS)N)rRr~rq)r:r!r!r" test_waitsz$TestTerminatedProcessLeaks.test_waitcsfdd}j|dS)NcsDytjjjStk r>}z|jtjkr.WYdd}~XnXdS)N)rrr~rarerrnoZESRCH)err)r:r!r"rTs  z7TestTerminatedProcessLeaks.test_proc_info..call)rR)r:rTr!)r:r"rs z)TestTerminatedProcessLeaks.test_proc_info)rXrYrZr[ classmethodrrr<rrrrrrr __classcell__r!r!)rr"rsrc@seZdZdZddZeddZeddZedd Zed d Z d d Z ee j e dddZddZe j edddZe j eoedddZe j eoedddZddZe j eoejjd dedd Zed!d"Zed#d$Ze j ed%e j eo&ejd&kd'd(d)Z d*d+Z!e j e"d,d-d.Z#ee j e$ dd/d0Z%ee j e& dd1d2Z'ee j e( dd3d4Z)ed5d6Z*e j e+d7d8d9Z,e+rd:d;Z-dd?Z/d@dAZ0dBdCZ1dDS)ETestModuleFunctionsLeaksz&Test leaks of psutil module functions.cCsHtd }x:tjD]0}|jsq||kr(q|jt|d||d qWdS) N version_info __version__ process_iter wait_procsrdcpu_times_percent cpu_countrs)rQ)rrrrrdrr)rtrv__all__islowerryrz)r:r{r|r!r!r"r}s z&TestModuleFunctionsLeaks.test_coveragecCs|jtjdddS)NT)logical)rRrvr)r:r!r!r"test_cpu_count_logicalsz/TestModuleFunctionsLeaks.test_cpu_count_logicalcCs|jtjdddS)NF)r)rRrvr)r:r!r!r"test_cpu_count_physicalsz0TestModuleFunctionsLeaks.test_cpu_count_physicalcCs|jtjdS)N)rRrvr)r:r!r!r"rsz'TestModuleFunctionsLeaks.test_cpu_timescCs|jtjdddS)NT)Zpercpu)rRrvr)r:r!r!r"test_per_cpu_timessz+TestModuleFunctionsLeaks.test_per_cpu_timescCs|jtjdS)N)rRrvZ cpu_stats)r:r!r!r"test_cpu_statssz'TestModuleFunctionsLeaks.test_cpu_statsz not supportedcCs|jtjdS)N)rRrvZcpu_freq)r:r!r!r" test_cpu_freqsz&TestModuleFunctionsLeaks.test_cpu_freqcCs|jtjdS)N)rRrvZvirtual_memory)r:r!r!r"test_virtual_memorysz,TestModuleFunctionsLeaks.test_virtual_memoryz&worthless on SUNOS (uses a subprocess)cCs|jtjdS)N)rRrvZ swap_memory)r:r!r!r"test_swap_memorysz)TestModuleFunctionsLeaks.test_swap_memoryz worthless on POSIX (pure python)cCs|jtjtjdS)N)rRrvZ pid_existsrr)r:r!r!r"test_pid_existssz(TestModuleFunctionsLeaks.test_pid_existscCs|jtjddS)N.)rRrvZ disk_usage)r:r!r!r"test_disk_usagesz(TestModuleFunctionsLeaks.test_disk_usagecCs|jtjdS)N)rRrvZdisk_partitions)r:r!r!r"test_disk_partitionssz-TestModuleFunctionsLeaks.test_disk_partitionsz/proc/diskstatsz3/proc/diskstats not available on this Linux versioncCs|jtjdddS)NF)nowrap)rRrvZdisk_io_counters)r:r!r!r"test_disk_io_counterssz.TestModuleFunctionsLeaks.test_disk_io_counterscCs|jtjdS)N)rRrvZpids)r:r!r!r" test_pidssz"TestModuleFunctionsLeaks.test_pidscCs|jtjdddS)NF)r)rRrvZnet_io_counters)r:r!r!r"test_net_io_counterssz-TestModuleFunctionsLeaks.test_net_io_countersz worthless on Linux (pure python)rzneed root accessc Cs"t|jtjWdQRXdS)N)r rRrvZnet_connections)r:r!r!r"test_net_connectionssz-TestModuleFunctionsLeaks.test_net_connectionscCs|jtjtrdndddS)NPi)rCi@)rRrvZ net_if_addrsr)r:r!r!r"test_net_if_addrssz*TestModuleFunctionsLeaks.test_net_if_addrszEPERM on traviscCs|jtjdS)N)rRrvZ net_if_stats)r:r!r!r"test_net_if_statssz*TestModuleFunctionsLeaks.test_net_if_statscCs|jtjdS)N)rRrvZsensors_battery)r:r!r!r"test_sensors_battery$sz-TestModuleFunctionsLeaks.test_sensors_batterycCs|jtjdS)N)rRrvZsensors_temperatures)r:r!r!r"test_sensors_temperatures)sz2TestModuleFunctionsLeaks.test_sensors_temperaturescCs|jtjdS)N)rRrvZ sensors_fans)r:r!r!r"test_sensors_fans.sz*TestModuleFunctionsLeaks.test_sensors_fanscCs|jtjdS)N)rRrvZ boot_time)r:r!r!r"test_boot_time5sz'TestModuleFunctionsLeaks.test_boot_timez(XXX produces a false positive on WindowscCs|jtjdS)N)rRrvZusers)r:r!r!r" test_users:sz#TestModuleFunctionsLeaks.test_userscCs|jtjdS)N)rRrZwinservice_enumerate)r:r!r!r"test_win_service_iterBsz.TestModuleFunctionsLeaks.test_win_service_itercCsdS)Nr!)r:r!r!r"test_win_service_getEsz-TestModuleFunctionsLeaks.test_win_service_getcCs"ttjj}|jtj|dS)N)nextrvwin_service_iterr|rRrZwinservice_query_config)r:r|r!r!r"test_win_service_get_configHsz4TestModuleFunctionsLeaks.test_win_service_get_configcCs"ttjj}|jtj|dS)N)rrvrr|rRrZwinservice_query_status)r:r|r!r!r"test_win_service_get_statusLsz4TestModuleFunctionsLeaks.test_win_service_get_statuscCs"ttjj}|jtj|dS)N)rrvrr|rRrZwinservice_query_descr)r:r|r!r!r" test_win_service_get_descriptionPsz9TestModuleFunctionsLeaks.test_win_service_get_descriptionN)2rXrYrZr[r}r#rrrrrrrr rrrrrr rrrrrpathexistsrrrrgetuidrrrrrrrrrrrrrrrrrrr!r!r!r"rsR   $r__main__):r[Z __future__rrrr8rrOrIrMrvZpsutil._commonrrrrrrZpsutil._compatr Z psutil.testsr r r r rrrrrrrrrrrrrrrrr]r\r^r Z _psplatformrrwrJr#r6ZTestCaser7r`rrrX__file__r!r!r!r" sl                            cB< PK!?2 #__pycache__/__main__.cpython-36.pycnu[3 JZ @s:dZddlZddlZddlZddlZddlZddlZyddlmZWn e k rdddl mZYnXddl m Z ddl m Z ejjejjeZdZgZejdddkrejd d d d gnVejdddksejdddkrejd dgn ejdddkrejd gddZdddZddZedS)z? Run unit tests. This is invoked by: $ python -m psutil.tests N)urlopen) PYTHON_EXE) run_suitez$https://bootstrap.pypa.io/get-pip.pyZ ipaddressZ unittest2argparsez mock==1.0.1ZmockcCsy ddl}Wntk rtjdd}tj|tdt|jft t drZt j }nd}|rlt |dni}t tf|}|j}|j||jtdtjdt|jf}|SQRXYnXdS) Nrz.py)suffixzdownloading %s to %s_create_unverified_context)contextzinstalling pipz %s %s --user)pip ImportErrortempfileZNamedTemporaryFile contextlibclosingprint GET_PIP_URLnamehasattrsslr dictrreadwriteflushossystemr)r fZctxkwargsZreqdatacoder! /usr/lib64/python3.6/__main__.py install_pip&s"       r#cCsV|dkr t}t|}|rRttd}|s*dnd}ttjdt|dj|f}|SdS)z"Install test dependencies via pip.NZ real_prefixz--userz!%s -m pip install %s --upgrade %s ) TEST_DEPSsetrsysr#rrrjoin)ZdepsZis_venvoptsr r!r!r"install_test_deps<s  r+c Csdt}tj|dd}|jdddddd |j\}}|jrJttnRxJtD]B}yt |j d d WqPt k rt j d |tfYqPXqPWtdS) Nz%s -m psutil.tests [opts]zrun unit tests)usage descriptionz-iz--install-deps store_trueFz%don't print status messages to stdout)actiondefaulthelpz==rz>%r lib is not installed; run %s -m psutil.tests --install-deps)roptparseZ OptionParserZ add_option parse_argsZ install_depsr#r+r& __import__splitrr(exitr)r,parserr*argsZdepr!r!r"mainJs   r9)rr)rr)r r)r r )N)__doc__rr2rrr(rZurllib.requestrrZurllib2Z psutil.testsrrpathabspathdirname__file__ZHERErr& version_infoextendr#r+r9r!r!r!r" s2  &  PK!?2 )__pycache__/__main__.cpython-36.opt-1.pycnu[3 JZ @s:dZddlZddlZddlZddlZddlZddlZyddlmZWn e k rdddl mZYnXddl m Z ddl m Z ejjejjeZdZgZejdddkrejd d d d gnVejdddksejdddkrejd dgn ejdddkrejd gddZdddZddZedS)z? Run unit tests. This is invoked by: $ python -m psutil.tests N)urlopen) PYTHON_EXE) run_suitez$https://bootstrap.pypa.io/get-pip.pyZ ipaddressZ unittest2argparsez mock==1.0.1ZmockcCsy ddl}Wntk rtjdd}tj|tdt|jft t drZt j }nd}|rlt |dni}t tf|}|j}|j||jtdtjdt|jf}|SQRXYnXdS) Nrz.py)suffixzdownloading %s to %s_create_unverified_context)contextzinstalling pipz %s %s --user)pip ImportErrortempfileZNamedTemporaryFile contextlibclosingprint GET_PIP_URLnamehasattrsslr dictrreadwriteflushossystemr)r fZctxkwargsZreqdatacoder! /usr/lib64/python3.6/__main__.py install_pip&s"       r#cCsV|dkr t}t|}|rRttd}|s*dnd}ttjdt|dj|f}|SdS)z"Install test dependencies via pip.NZ real_prefixz--userz!%s -m pip install %s --upgrade %s ) TEST_DEPSsetrsysr#rrrjoin)ZdepsZis_venvoptsr r!r!r"install_test_deps<s  r+c Csdt}tj|dd}|jdddddd |j\}}|jrJttnRxJtD]B}yt |j d d WqPt k rt j d |tfYqPXqPWtdS) Nz%s -m psutil.tests [opts]zrun unit tests)usage descriptionz-iz--install-deps store_trueFz%don't print status messages to stdout)actiondefaulthelpz==rz>%r lib is not installed; run %s -m psutil.tests --install-deps)roptparseZ OptionParserZ add_option parse_argsZ install_depsr#r+r& __import__splitrr(exitr)r,parserr*argsZdepr!r!r"mainJs   r9)rr)rr)r r)r r )N)__doc__rr2rrr(rZurllib.requestrrZurllib2Z psutil.testsrrpathabspathdirname__file__ZHERErr& version_infoextendr#r+r9r!r!r!r" s2  &  PK!Y /n/n-__pycache__/test_windows.cpython-36.opt-1.pycnu[3 JZK@s`dZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl m Z ddlmZddlmZddlmZddlmZddlmZdd lmZdd lmZdd lmZdd lmZdd lmZe jZe jdy$ddlZddlZddlZddlZWn$e k rDej!dkr@YnXWdQRXe j"j#Z#e j$d$kZ%ddZ&ej'e dGdddej(Z)ej'e dGdddej(Z*ej'e dGdddej(Z+ej'e dGdddej(Z,ej'e dGdddej(Z-ej'e dGdd d ej(Z.ej'e dGd!d"d"ej(Z/e0d#kr\ee1dS)%zWindows specific tests.N)WINDOWS)callable)APPVEYOR)get_test_subprocess) HAS_BATTERY)mock) reap_children)retry_before_failing)run_test_module_by_name)sh)unittestignorent csfdd}|S)Ncsty|f||Stk rn}zBddlm}|j|krDtjdd|jtjkr\tjddWYdd}~XnXdS)Nr)ACCESS_DENIED_SET)OSErrorZpsutil._pswindowsrerrnopsutil AccessDeniedZESRCH NoSuchProcess)selfargskwargserrr)fun$/usr/lib64/python3.6/test_windows.pywrapper5s     z wrap_exceptions..wrapperr)rrr)rrwrap_exceptions4s rz WINDOWS onlyc@seZdZddZejdejkdddZddZ d d Z d d Z eje d e ddZe ddZddZddZddZddZddZdS)TestSystemAPIscCsVtd}tjddj}x8|D]0}d|jddjkr8q||kr|jd|qWdS)Nz ipconfig /allT)Zperniczpseudo-interface -z-%r nic wasn't found in 'ipconfig /all' output)r rZnet_io_counterskeysreplacelowerfail)routZnicsZnicrrrtest_nic_namesJs zTestSystemAPIs.test_nic_namesNUMBER_OF_PROCESSORSz-NUMBER_OF_PROCESSORS env var is not availablecCs"ttjd}|j|tjdS)Nr))intosenviron assertEqualr cpu_count)rZnum_cpusrrrtest_cpu_countTszTestSystemAPIs.test_cpu_countcCs$tjd}tj}|j||dS)N)win32apiZ GetSystemInforr.r-)r sys_value psutil_valuerrrtest_cpu_count_2Zs zTestSystemAPIs.test_cpu_count_2cCs@tj}|jd}|j|jtjj|j|jtjj dS)Nr) wmiWMIZWin32_Processorr-ZCurrentClockSpeedrZcpu_freqZcurrentZ MaxClockSpeedmax)rwprocrrr test_cpu_freq_s zTestSystemAPIs.test_cpu_freqcCs,tjjd}|jt|jtjjdS)Nr) r5r6ZWin32_ComputerSystemr-r*ZTotalPhysicalMemoryrZvirtual_memorytotal)rr8rrrtest_total_phymemes z TestSystemAPIs.test_total_phymemztest not relieable on appveyorcCs:tjj}tdd|D}ttj}|j||dS)NcSsg|] }|jqSr) ProcessId).0xrrr |sz,TestSystemAPIs.test_pids..)r5r6 Win32_ProcesssetrZpidsr-)rr8Zwmi_pidsZ psutil_pidsrrr test_pidsvs  zTestSystemAPIs.test_pidscCstjdd}tjj}x|D]}x|D]}|jjdd|jkr(|jsHPytj |j}Wn4t k r}z|j t j krzPnWYdd}~XnX|j |jt|jt|j}|j |j|t|j|d kr|jd|j|fPq(W|jdt|qWdS) NT)all\ izpsutil=%s, wmi=%szcan't find partition %si(i)rdisk_partitionsr5r6ZWin32_LogicalDiskZdevicer$ZDeviceID mountpoint disk_usagerrENOENTr-r;r*ZSizeZ FreeSpacefreeabsr&repr)rZps_partsZ wmi_partsZps_partZwmi_partZusagerZwmi_freerrr test_diskss*      zTestSystemAPIs.test_diskscCspxjtjD]^}tj|j}tj|j}|j|d|jdd|j|d|jdd|j |j |j|jq WdS)Nri)deltaii) rrHr1ZGetDiskFreeSpaceExrIrJassertAlmostEqualrLr;r-Zused)rZdiskr2r3rrrtest_disk_usages  zTestSystemAPIs.test_disk_usagecCs>ddtjjdD}ddtjddD}|j||dS)NcSs$g|]}|r|jd r|dqS)zA:rE) startswith)r>r?rrrr@sz7TestSystemAPIs.test_disk_partitions..z\cSsg|] }|jqSr)rI)r>r?rrrr@sT)rD)r1ZGetLogicalDriveStringssplitrrHr-)rr2r3rrrtest_disk_partitionssz#TestSystemAPIs.test_disk_partitionscCs`ttj}tjj}t}x$|D]}|j|j|j|jq$W|j ||@d||fdS)Nzno common entries in %s, %s) rBcextZ net_if_statsr5r6ZWin32_NetworkAdapteraddNameZNetConnectionID assertTrue)rZps_namesZ wmi_adaptersZ wmi_namesZ wmi_adapterrrrtest_net_if_statss     z TestSystemAPIs.test_net_if_statscCs^tjj}|djjdd}tjj|d}tjjtj }t ||j }|j |ddS)Nr.z %Y%m%d%H%M%S) r5r6ZWin32_OperatingSystemZLastBootUpTimerUdatetimeZstrptimeZ fromtimestampr boot_timerMZ total_secondsZassertLessEqual)rZwmi_osZ wmi_btime_strZ wmi_btime_dtZ psutil_dtZdiffrrrtest_boot_times zTestSystemAPIs.test_boot_timecCstjddd|jtjdWdQRXtjddd|jtjdWdQRXtjddd|jtjdWdQRXtjddd|jtjdWdQRXdS)Nz psutil._pswindows.cext.boot_timer0) return_valueiM)rpatchr-rr_)rrrrtest_boot_time_fluctuationsz)TestSystemAPIs.test_boot_time_fluctuationN)__name__ __module__ __qualname__r(r skipIfr+r,r/r4r:r<rr rCrOrSrVr[r`rerrrrr Gs      r c@s`eZdZddZeje dddZeje dddZdd Z d d Z d d Z ddZ dS)TestSensorsBatterycCs.tjdr|jtjn|jtjdS)NZSystemBatteriesPresent)r1ZGetPwrCapabilitiesZassertIsNotNonersensors_battery assertIsNone)rrrrtest_has_batterys z#TestSensorsBattery.test_has_batteryz no batterycCs6tj}|jdd}tj}|j|j|jdddS)Nzselect * from Win32_BatteryrrQ)rP)r5r6queryrrkrRZpercentZEstimatedChargeRemaining)rr8 battery_wmibattery_psutilrrr test_percents zTestSensorsBattery.test_percentcCs6tj}|jdd}tj}|j|j|jdkdS)Nzselect * from Win32_Batteryrr)r5r6rnrrkr-Z power_pluggedZ BatteryStatus)rr8rorprrrtest_power_pluggeds z%TestSensorsBattery.test_power_pluggedc Cs,tjddd}|jtjWdQRXdS)Nz&psutil._pswindows.cext.sensors_batteryr)ra)rrsrr)rrdrlrrk)rmrrrtest_emulate_no_batterys z*TestSensorsBattery.test_emulate_no_batteryc Cs2tjddd}|jtjjtjWdQRXdS)Nz&psutil._pswindows.cext.sensors_batteryrQr)ra)rQrrr)rrdr-rrksecsleftPOWER_TIME_UNLIMITED)rrtrrrtest_emulate_power_connecteds   z/TestSensorsBattery.test_emulate_power_connectedc Cs2tjddd}|jtjjtjWdQRXdS)Nz&psutil._pswindows.cext.sensors_batteryr)ra)rryrr)rrdr-rrkrvrw)rrtrrrtest_emulate_power_chargings   z.TestSensorsBattery.test_emulate_power_chargingc Cs2tjddd}|jtjjtjWdQRXdS)Nz&psutil._pswindows.cext.sensors_batteryrrQ)ra)rrrr{)rrdr-rrkrvZPOWER_TIME_UNKNOWN)rrtrrrtest_emulate_secs_left_unknowns   z1TestSensorsBattery.test_emulate_secs_left_unknownN) rfrgrhrmr rirrqrrrurxrzr|rrrrrjs  rjc@seZdZeddZeddZddZddZd d Zd d Z d dZ ddZ ddZ e jejd+k dddZddZddZddZddZd d!Zd"d#Zd$d%Zd&d'Zd(d)Zd*S), TestProcesscCstj|_dS)N)rpid)clsrrr setUpClassszTestProcess.setUpClasscCs tdS)N)r)rrrr tearDownClassszTestProcess.tearDownClasscCstjd}|jtj|jdS)Nr)rProcess assertRaisesrkill)rprrr test_issue_24s zTestProcess.test_issue_24c Cstjd}|j|jdt||j|j|jdky|jdd\}}Wn(tj k r|t j dd krxYnX|j|d kdS) NrbZSystemgrrQvistawin-7win7r)rrr) rrr-namestrusernamerZ create_time memory_inforplatformuname)rrrssvmsrrrtest_special_pid s zTestProcess.test_special_pidcCs"tj|j}|jt|jtjdS)N)rrr~r ValueError send_signalsignalSIGINT)rrrrrtest_send_signal1s zTestProcess.test_send_signalc CsNxHtjD]<}y |jtjj|j|jWq tjk rDYq Xq WdS)N) r process_iterr-r+pathbasenameexerError)rrrrrtest_exe5s  zTestProcess.test_execCsbtjtj}|j}tjtjtj tj}|j}|j ||dtj ||j |j|dS)NrQ) rrr+getpid num_handlesr1 OpenProcesswin32conPROCESS_QUERY_INFORMATIONFALSEr- CloseHandle)rrZbeforehandleafterrrrtest_num_handles_increment<s z&TestProcess.test_num_handles_incrementc sfdd}tj|j}g}xttjD]jds(dkrBq(q(y(|||j}|||j}Wntjtjfk rYq(X||kr(d||f}|j|q(W|r|j ddj |dS)Ncs,t|d}|dk r$t|r$|n|dS)N)getattrr)rattr)rrrcallJs z+TestProcess.test_handles_leak..call_ terminatersuspendresumenicerwaitchildrenas_dictmemory_info_exz@failure while processing Process.%s method (before=%s, after=%s) ) rrrrrrrrrr) rrr~dirrTrrrappendr&join)rrrZfailuresZnum1Znum2r&r)rrtest_handles_leakFs,       zTestProcess.test_handles_leakc Cs:x4tjD](}y |jWq tjk r0Yq Xq WdS)N)rrrr)rrrrrtest_name_always_availablejs  z&TestProcess.test_name_always_availablerzCTRL_* signals not supportedcCsbtjtj}|jtj|jtj|j|j |j tj |jtj|j tj |jtjdS)N) rrrr~rrZ CTRL_C_EVENTZCTRL_BREAK_EVENTrrrr)rrrrrtest_ctrl_signalsss   zTestProcess.test_ctrl_signalsc Cs\xVtjD]J}ytjj|j}|j}Wntjtjfk rFYq X|j ||q WdS)N) rrr+rrrrrrr-)rrabrrrtest_compare_name_exes z!TestProcess.test_compare_name_execCs |jtjjtjtjdS)N)r-rrrr1Z GetUserNameExrZNameSamCompatible)rrrr test_usernameszTestProcess.test_usernamecCs8tjddtjj}djtjj}|j ||dS)Nz +r!) resubr1ZGetCommandLinestriprrrcmdliner-)rr2r3rrr test_cmdlineszTestProcess.test_cmdlinecCsJtjtjtjtj}|jtj|t j |}t j j }|j||dS)N)r1rrrrr+r addCleanupr win32processZGetPriorityClassrrrr-)rrr2r3rrr test_nices   zTestProcess.test_nicecCstjtjtj|j}|jtj|tj |}t j |jj }|j |d|j|j |d|j|j |d|j|j |d|j|j |d|j|j |d|j|j |d|j|j |d|j|j |j|j|j |j|jdS) NZPeakWorkingSetSizeWorkingSetSizeZQuotaPeakPagedPoolUsageZQuotaPagedPoolUsageZQuotaPeakNonPagedPoolUsageZQuotaNonPagedPoolUsageZ PagefileUsageZPeakPagefileUsage)r1rrrrr~rrrZGetProcessMemoryInforrrr-Z peak_wsetZwsetZpeak_paged_poolZ paged_poolZpeak_nonpaged_poolZ nonpaged_poolZpagefileZ peak_pagefilerr)rrr2r3rrrtest_memory_infos0  zTestProcess.test_memory_infocCsXtjtjtj|j}|jtj|tj |j}|j |j }t j |}|j||dS)N)r1rrrrr~rrrrrrrZGetExitCodeProcessr-)rrrr3r2rrr test_waits   zTestProcess.test_waitcCs\dd}tjtjtj|j}|jtj||tj |d}t j |jj }|j ||dS)NcsfddtdDS)Ncsg|]}d|>@r|qS)rQr)r>i)r?rrr@szGTestProcess.test_cpu_affinity..from_bitmask..@)range)r?r)r?r from_bitmasksz3TestProcess.test_cpu_affinity..from_bitmaskr)r1rrrrr~rrrZGetProcessAffinityMaskrrZ cpu_affinityr-)rrrr2r3rrrtest_cpu_affinitys zTestProcess.test_cpu_affinitycCstjtjtjtj}|jtj|t j |}t j j }|j|j|d|j|j|d|j|j|d|j|j|d|j|j|d|j|j|ddS)NZReadOperationCountZWriteOperationCountZReadTransferCountZWriteTransferCountZOtherOperationCountZOtherTransferCount)r1rrrrr+rrrrZGetProcessIoCountersrr io_countersr-Z read_countZ write_countZ read_bytesZ write_bytes other_countZ other_bytes)rrr2r3rrrtest_io_counterss"  zTestProcess.test_io_counterscCsddl}ddl}d}|jjj|dtj}|j|jjj||j j }|jjj ||j ||j }tjj}|jjj||j||ddS)NrirQ)ctypesZctypes.wintypesZwindllZkernel32rr+rrrZwintypesZDWORDZGetProcessHandleCountZbyrefvaluerrrr-)rrrrZhndcntr2r3rrrtest_num_handless  zTestProcess.test_num_handlesN)rr)rfrgrh classmethodrrrrrrrrrr risys version_inforrrrrrrrrrrrrrr}s(   $     r}c@s`eZdZdZeddZeddZddZdd Zd d Z d d Z ddZ ddZ ddZ dS)TestProcessWMIz%Compare Process API results with WMI.cCstj|_dS)N)rr~)rrrrrszTestProcessWMI.setUpClasscCs tdS)N)r)rrrrrszTestProcessWMI.tearDownClasscCs8tjj|jdd}tj|j}|j|j|jdS)N)r=r) r5r6rAr~rrr-rZCaption)rr8rrrr test_name s zTestProcessWMI.test_namecCs@tjj|jdd}tj|j}|j|jj|j jdS)N)r=r) r5r6rAr~rrr-rr%ZExecutablePath)rr8rrrrrs zTestProcessWMI.test_execCsFtjj|jdd}tj|j}|jdj|j|j j dddS)N)r=rr!"rF) r5r6rAr~rrr-rrZ CommandLiner$)rr8rrrrrs zTestProcessWMI.test_cmdlinecCsPtjj|jdd}tj|j}|j\}}}d||f}|j|j|dS)N)r=rz%s\%s) r5r6rAr~rrZGetOwnerr-r)rr8rZdomainrrrrrrs   zTestProcessWMI.test_usernamecCsLtjdtjj|jdd}tj|j}|jj }|j |t |j dS)Ng?)r=r) timesleepr5r6rAr~rrrrr-r*r)rr8rrrrrtest_memory_rss#s    zTestProcessWMI.test_memory_rsscCsjtjdtjj|jdd}tj|j}|jj }t |j }||krf||dkrf|j d||fdS)Ng?)r=rizwmi=%s, psutil=%s) rrr5r6rAr~rrrrr*Z PageFileUsager&)rr8rrZ wmi_usagerrrtest_memory_vms*s    zTestProcessWMI.test_memory_vmscCs\tjj|jdd}tj|j}t|jjdd}t j dt j |j }|j ||dS)N)r=rr\z %Y%m%d%H%M%S)r5r6rAr~rrrZ CreationDaterUrZstrftimeZ localtimerr-)rr8rZ wmic_createZ psutil_createrrrtest_create_time7s  zTestProcessWMI.test_create_timeN)rfrgrh__doc__rrrrrrrrrrrrrrrs   rc@sXeZdZdZeddZeddZddZdd Zd d Z d d Z ddZ ddZ dS)TestDualProcessImplementationa{ Certain APIs on Windows have 2 internal implementations, one based on documented Windows APIs, another one based NtQuerySystemInformation() which gets called as fallback in case the first fails because of limited permission error. Here we test that the two methods return the exact same value, see: https://github.com/giampaolo/psutil/issues/304 cCstj|_dS)N)rr~)rrrrrLsz(TestDualProcessImplementation.setUpClasscCs tdS)N)r)rrrrrPsz+TestDualProcessImplementation.tearDownClassc CsPtj|jj}tjdtjtjd}|j tj|jj|WdQRXdS)Nz psutil._psplatform.cext.proc_exe) side_effect) rrr~rrrdrr+rr-)rrrrrrrWs z'TestDualProcessImplementation.test_namec Cstj|jj}tjdttjddx}tj|jj}|j t |t |xLt t |D]<}|j ||d|j ||d|j ||||ddqZWWdQRXdS)Nz(psutil._psplatform.cext.proc_memory_infomsg)rri)rP)rrr~rrrdrrEPERMr-lenrZassertGreaterEqualrR)rZmem_1rZmem_2rrrrr^sz.TestDualProcessImplementation.test_memory_infoc CsNtj|jj}tjdttjdd}|j tj|jj|WdQRXdS)Nz(psutil._psplatform.cext.proc_create_timer)r) rrr~rrrdrrrr-)rZctimerrrrrjs z.TestDualProcessImplementation.test_create_timec Csntj|jj}tjdttjdd>}tj|jj}|j |j |j dd|j |j |j ddWdQRXdS)Nz&psutil._psplatform.cext.proc_cpu_timesr)rg{Gz?)rP) rrr~Z cpu_timesrrdrrrrRusersystem)rZ cpu_times_1rZ cpu_times_2rrrtest_cpu_timesqsz,TestDualProcessImplementation.test_cpu_timesc Csttj|jj}tjdttjddD}tj|jj}x,t t |D]}|j ||||ddqFWWdQRXdS)Nz(psutil._psplatform.cext.proc_io_countersr)rr0)rP) rrr~rrrdrrrrrrR)rZ io_counters_1rZ io_counters_2rrrrr|sz.TestDualProcessImplementation.test_io_countersc CsNtj|jj}tjdttjdd}|j tj|jj|WdQRXdS)Nz(psutil._psplatform.cext.proc_num_handlesr)r) rrr~rrrdrrrr-)rrrrrrrs z.TestDualProcessImplementation.test_num_handlesN) rfrgrhrrrrrrrrrrrrrrr@s      rc@s|eZdZdZeddZeddZddgZdd Z d d Z ed d Z ddZ ddZ ddZddZddZddZdS)RemoteProcessTestCasezCertain functions require calling ReadProcessMemory. This trivially works when called on the current process. Check that this works on other processes, especially when they have a different bitness. cCsTd}xJtjdD]<}tj|d|gtjtjd}|j\}}|tt kr|SqWdS)Nz6import sys; sys.stdout.write(str(sys.maxsize > 2**32))zC:\Python*\python.exez-c)rstdoutstderr)glob subprocessPopenPIPEZSTDOUT communicater IS_64_BIT)codefilenamer9outputrrrrfind_other_interpreters   z,RemoteProcessTestCase.find_other_interpretercCs@|j}|dkrtjdtr.tj|_||_n||_tj|_dS)Nz0could not find interpreter with opposite bitness)rr ZSkipTestrr executablepython64python32)rZ other_pythonrrrrsz RemoteProcessTestCase.setUpClassz-czimport sys; sys.stdin.read()cCsVtjj}ttj|d<t|jg|j|tj d|_ t|j g|j|tj d|_ dS)NTHINK_OF_A_NUMBER)envstdin) r+r,copyrrrr test_argsrrproc32rproc64)rrrrrsetUps  zRemoteProcessTestCase.setUpcCs|jj|jjtdS)N)rrrr)rrrrtearDowns  zRemoteProcessTestCase.tearDowncCs tdS)N)r)rrrrrsz#RemoteProcessTestCase.tearDownClasscCs@tj|jj}|jt|jd|j|jdd|jdS)Nr]rQ)rrrr~r-rrr)rrrrrtest_cmdline_32sz%RemoteProcessTestCase.test_cmdline_32cCs@tj|jj}|jt|jd|j|jdd|jdS)Nr]rQ)rrrr~r-rrr)rrrrrtest_cmdline_64sz%RemoteProcessTestCase.test_cmdline_64cCs&tj|jj}|j|jtjdS)N)rrrr~r-cwdr+getcwd)rrrrr test_cwd_32sz!RemoteProcessTestCase.test_cwd_32cCs&tj|jj}|j|jtjdS)N)rrrr~r-rr+r)rrrrr test_cwd_64sz!RemoteProcessTestCase.test_cwd_64cCs>tj|jj}|j}|jd||j|dttj dS)Nr) rrrr~r,assertIn assertEqualsrr+r)rrerrrtest_environ_32s z%RemoteProcessTestCase.test_environ_32cCs>tj|jj}|j}|jd||j|dttj dS)Nr) rrrr~r,r r rr+r)rrr rrrtest_environ_64s z%RemoteProcessTestCase.test_environ_64N)rfrgrhr staticmethodrrrrrrrrrrr r rrrrrrs    rc@seZdZddZddZdS) TestServicescCsntdddddddg}tdd d g}tddd d d ddg}x,tjD]}|j}|j|dt|j|djd|j|dt|j|dt|j|d||ddk rtj |d|j|dt|j|dt|j|dt|j|d||j|d||j|dt|j }|dk rLtj |}|j |j tj |j}|j||qFWdS)NZrunningZpausedstartpausecontinuestopZstoppedZ automaticZmanualZdisabledZ start_pendingZ pause_pendingZcontinue_pendingZ stop_pendingrrF display_namerstatusr~ZbinpathZ start_type description)rBrwin_service_iterrZassertIsInstancerZassertNotEqualrr rr~rZZ is_runningwin_service_getrr-)rZvalid_statusesZvalid_start_typesZservdatar~rsrrrtest_win_service_itersR   z"TestServices.test_win_service_iterc'Cspttjj}|jtj}tj|dWdQRX|j|jj|dtj|}t tj j j d}t jd|d|jtj|jWdQRXt jd|d|jtj|jWdQRXt tj j jd}t jd|d|jtj|jWdQRXt jd|d|jtj|jWdQRX|j|jt||j|jt||j|jt||j|jt|dS)Nz???rFz/psutil._psplatform.cext.winservice_query_status)rz/psutil._psplatform.cext.winservice_query_config)nextrrrrrrr-Z exceptionZ WindowsError _psplatformrWZERROR_SERVICE_DOES_NOT_EXISTrrdrrZERROR_ACCESS_DENIEDrr rrrN)rrcmZserviceexcrrrtest_win_service_get!s2     z!TestServices.test_win_service_getN)rfrgrhrr!rrrrrs0r__main__l)2rr^rrr+rrrrrrwarningsrrZpsutil._compatrZ psutil.testsrrrrrr r r r catch_warnings simplefilterr1rrr5 ImportErrorrrrWmaxsizerrriZTestCaser rjr}rrrrrf__file__rrrrsl                   < m A N ^ U PK! &+__pycache__/test_sunos.cpython-36.opt-1.pycnu[3 JZ@sxdZddlZddlZddlmZddlmZddlmZddlmZeje dGdd d ej Z e d krtee dS) zSun OS specific tests.N)SUNOS)run_test_module_by_name)sh)unittestz SUNOS onlyc@seZdZddZddZdS)SunOSSpecificTestCasec Cstdtjd}|jjddd}|s4tdd}}xL|D]D}|j}|d d\}}|tt|d7}|tt|d7}qBW||}tj} |j | j ||j | j ||j | j |dS) Nz#env PATH=/usr/sbin:/sbin:%s swap -lPATH zno swap device(s) configuredri) rosenvironstripsplit ValueErrorintpsutilZ swap_memory assertEqualtotalusedfree) selfoutlinesrrlinetfrZ psutil_swapr"/usr/lib64/python3.6/test_sunos.pytest_swap_memorys z&SunOSSpecificTestCase.test_swap_memorycCs&td}|jtjt|jddS)Nz/usr/sbin/psrinfor)rrr cpu_countlenr)rrrrrtest_cpu_count&sz$SunOSSpecificTestCase.test_cpu_countN)__name__ __module__ __qualname__rr"rrrrrsr__main__) __doc__r rrZ psutil.testsrrrZskipIfZTestCaserr#__file__rrrrs     PK!tt#__pycache__/__init__.cpython-36.pycnu[3 JZL@sdZddlmZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl Z ddlZddlZddlZddlZddlZddlZddlZddlZddlZddl mZddl mZddl mZddl mZddlZddlmZdd lmZdd lmZdd lmZdd l m!Z!dd l"m#Z#ddl"m$Z$ddl"m%Z%ddl"m&Z&ej'dkrjddl(Z)nddl)Z)yddl)m*Z*Wne+k rddl*Z*YnXej'dkrddl,Z,ndZ,ddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;dd?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYgDZ-ej.d"pZdZdkZ/d]ej0kZ1erpdndZ2e3ej4j5d#Z6e3ej4j5dZ7d_Z8dZ9dZ:ej.dbse/rdcndZ;e6se7re8d9Z8e:d9Z:ddZej=j?ej@e<ZAeAdeZBeAe$dfZCejDjEdkZFej=jGej=j>ej=jHeIdidiZJej=j>eJdjZKej=jGej=jHeIZLeMejNdkZOeMedlZPeoze ZQeMejNdmZReMejNdnZSeMejNdoZTdpejNjUjVkZWeMejNdqZXeMejNdrZYeMejNdsZZeMejNdtZ[eMeduZ\e\oej]Z^eMedvZ_eMedwZ`dxdyZaeaZbecejddzZed{d|efeDZgehe d}eiZjehe d~eiZkelZmelZnelZoejpddZqejpddZrGdddejsZtddZueuddd5Zveudd7Zwdd6Zxeudd3ZyeuddZzddd4Z{ddHZ|ddGZ}GdddeiZ~e~ejde:ddddJZe~eefde:dddddKZe~ede:ddddIZddBZddZejddAZdddCZeZdd<Ze8fdd;Zddd9Zddd:ZdddNZejdddOZeedfddPZe jfddQZdddRZddSZejddTZddMZddLZddUZddVZddWZddYZereje.attemptz python%s.%srz"can't find python exe real abspath)rsys executableospathrealpathr version_infopsutilProcessrf ValueErrorexistsAssertionError)rirfrgrgrh _get_py_exes  ruzr+cCs g|]}|jdrtt|qS)ZSTATUS_) startswithgetattrrp).0xrgrgrh srzAF_UNIXSOCK_SEQPACKETc CstjxbtjtdD]P}t|tr0tt}nt}|j|ry t |Wqt k rft j YqXqWx6t D].}y t |Wqrt k rt j YqrXqrWdS)N.)rcloserllistdirr isinstancerrrvr>re traceback print_exc_testfiles_created)nameprefixrmrgrgrh_cleanup_filess      rcCstdddS)NT) recursive)r3rgrgrgrh_cleanup_procssrc@sHeZdZdZddZddZddZdd Zd d Zd d Z ddZ dS) ThreadTaskz6A thread task which does nothing expect staying alive.cCs&tjj|d|_d|_tj|_dS)NFgMbP?) threadingThread__init___running _intervalZEvent_flag)selfrgrgrhrs zThreadTask.__init__cCs|jj}d||jt|fS)Nz<%s running=%s at %#x>) __class____name__rid)rrrgrgrh__repr__szThreadTask.__repr__cCs |j|S)N)start)rrgrgrh __enter__szThreadTask.__enter__cOs |jdS)N)stop)rargskwargsrgrgrh__exit__szThreadTask.__exit__cCs(|jrtdtjj||jjdS)zStart thread and keep it running until an explicit stop() request. Polls for shutdown every 'timeout' seconds. zalready startedN)rrrrrrrwait)rrgrgrhrs zThreadTask.startcCs,d|_|jjx|jr&tj|jqWdS)NT)rrsettimesleepr)rrgrgrhrun s zThreadTask.runcCs |jstdd|_|jdS)z8Stop thread execution and and waits until it is stopped.zalready stoppedFN)rrrjoin)rrgrgrhrszThreadTask.stopN) r __module__ __qualname____doc__rrrrrrrrgrgrgrhrs rcstjfdd}|S)Nc s,y ||Stk r&tYnXdS)N)rer3)rr)funrgrhwrappers  z _cleanup_on_err..wrapper) functoolswraps)rrrg)rrh_cleanup_on_errsrcKs|jdt|jdt|jdtj|jdtjtrF|jdd|dkrttdt}td |g}t j |f|}t j |t td d d n"t j |f|}t j |t|j|S) a{Creates a python subprocess which does nothing for 60 secs and return it as subprocess.Popen instance. If "cmd" is specified that is used instead of python. By default stdin and stdout are redirected to /dev/null. It also attemps to make sure the process is in a reasonably initialized state. The process is registered for cleanup on reap_children(). stdinr`cwdenv creationflagsiNz:from time import sleep;open(r'%s', 'w').close();sleep(60);z-cT)deleteempty) setdefaultrrlgetcwdr]r r>_TESTFNrrbPopen_subprocesses_startedaddrErDpid)cmdkwdsZpylineZsprocrgrgrhr4)s$       cCstjjtd}tjd|tf}tr4t|dd}nt|}t j |j }t |ddd}tj |t|}tj|t j |}||fS)aCreate a subprocess which creates another one as in: A (us) -> B (child) -> C (grandchild). Return a (child, grandchild) tuple. The 2 processes are fully initialized and will live for 60 secs and are registered for cleanup on reap_children(). 2a import subprocess, os, sys, time s = "import os, time;" s += "f = open('%s', 'w');" s += "f.write(str(os.getpid()));" s += "f.close();" s += "time.sleep(60);" subprocess.Popen(['%s', '-c', s]) time.sleep(60) r)rF)rr)rlrmbasenamertextwrapdedentrr r2rprqrrEremoveint _pids_startedr)Z_TESTFN2ssubpZchild1dataZ child2_pidZchild2rgrgrhr6Js     cstjs ttrtjtdnt}tj d|}t j t j t j }|jt|j||jdt||j\}}zNtj|jgggtt|jd}tj|tj|tfddd|S|jXWdQRXdS) z+Create a zombie process and return its PID.)ra import os, sys, time, socket, contextlib child_pid = os.fork() if child_pid > 0: time.sleep(3000) else: # this is the zombie process s = socket.socket(socket.AF_UNIX) with contextlib.closing(s): s.connect('%s') if sys.version_info < (3, ): pid = str(os.getpid()) else: pid = bytes(str(os.getpid()), 'ascii') s.sendall(pid) rYicsjS)N)statusrg)zprocrgrhsz$create_zombie_proc..zret == psutil.STATUS_ZOMBIEN)rprrtrtempfilemktemprrrr contextlibclosingsocketr{Z settimeoutrbindlistenr2acceptselectfilenorZrecvrrrqrCr~)Z unix_filesrcsockconn_Zzpidrg)rrhr5ms$        c Ksr|jdd|jddtjtddd@}tj|j|j||jt t |jgf|}t |j WdQRX|S)zeRun python 'src' code string in a separate interpreter. Returns a subprocess.Popen instance. r`NrawtF)rmoder) rrNamedTemporaryFilerrrrwriteflushr4rrDr)rrfrrgrgrhr2s    cKst|ttfrdnd}tr"|r"dnd}|jd||jdtj|jdtj|jdd|jd |tj|f|}tj ||j \}}|j dkrt ||rt ||jd r|d d }|S)zUrun cmd in a subprocess and return its output. raises RuntimeError on error. TFirshellr`raZuniversal_newlinesr NrY)rstrrr rrbrdrrrZ communicate returncode RuntimeErrorrQendswith)rrrflagspr`rargrgrhshs"        rFc 'Cs*dd}|r"ttjjdd}nt}xtrtj}tj|jy |j Wn0t k r~}z|j t j krnWYdd}~XnX|j r|j j|jr|jjz|jr|jjWdy |jWn0t k r}z|j t jkrWYdd}~XnXXq*WxLtrFtj}ytj|}Wn tjk r8||YqX|j|qW|r&x4|D],}y |j Wntjk r|YnXqTWtj|td\}}x@|D]8}td|y |jWntjk rYnXqWtj|td\}}|r x|D]}td|qWx|D]}||jqWdS) a#Terminate and wait() any subprocess started by this test suite and ensure that no zombies stick around to hog resources and create problems when looking for refleaks. If resursive is True it also tries to terminate and wait() all grandchildren started by this process. c Ssttj| st||tjks(t|y tj|}|j sFt|Wntjk r^YnXdsptd|dS)Nrzpid %s is not gone)rpZ pid_existsrtZpidsrqZ is_running NoSuchProcess)rrrgrgrh assert_gones z"reap_children..assert_goneT)rN)timeoutz0couldn't terminate process %r; attempting kill()zprocess %r survived kill())rrprqchildrenrpoprrrZ terminateOSErrorerrnoZESRCHr`r~rarrZECHILDrZ wait_procsrrQkill) rrrrerrrrZgonealivergrgrhr3sd                 cCsts tdd}tjd}x(|D] }|js6|dkr@||7}q"Pq"W|sVtd|d}d}|jd}t|d}t|dkrt|d}t|dkrt|d}|||fS) z"Return a tuple such as (2, 6, 36).z not POSIXrTrr}zcan't parse %rrrYr) rNotImplementedErrorrlunameisdigitrrsplitrlen)rrcminormicroZnumsmajorrgrgrhrBs&          cCsdts tdtj}t|dr*|jp&d}n(tjd|d}|rNt|j d}nd}|d|d|fS)Nz not WINDOWSservice_pack_majorrz\s\d$rrY) r rrjZgetwindowsversionhasattrrresearchrgroup)ZwvZsprrgrgrhrA3s  c@s@eZdZdZedddddfddZdd Zd d Zd d ZdS)retryzA retry decorator.NgMbP?cCst|tjdS)N)file)printrjra)rrgrgrhrOszretry.cCs2|r|rtd||_||_||_||_||_dS)Nz/timeout and retries args are mutually exclusive)rr exceptionrretriesintervallogfun)rrrrrrrgrgrhrJszretry.__init__ccs`|jr.tj|j}xFtj|kr*dVqWn.|jrPx&t|jD] }dVq@Wn x dVqRWdS)N)rrrrange)rZstop_atrrgrgrh__iter__Ys  zretry.__iter__cCs|jdk rtj|jdS)N)rrr)rrgrgrhres z retry.sleepcs"tjfdd}|_|S)Ncstd}x^D]V}y ||Sjk r^}z(|}jdk rDj|jw WYdd}~Xq Xq Wtrn|ndS)N)rrrr )rrexcr)rrrgrhrjs    zretry.__call__..wrapper)rr decorator)rrrrg)rrrh__call__iszretry.__call__) rrrrrerrrrrgrgrgrhrGs  rgMbP?)rrrrcCstj|trtjddS)zWait for pid to show up in the process list then return. Used in the test suite to give time the sub process to initialize. g{Gz?N)rprqr rr)rrgrgrhrDs Tc Cs<t|d}|j}WdQRX|s*|s*t|r8tj||S)z8Wait for a file to be written on disk with some content.rbN)openreadrtrlr)ZfnamerrrrrgrgrhrEs  cCs|}t|st|S)zVKeep calling function for timeout secs and exit if eval() expression is True. )evalrt)rexprretrgrgrhrCs cCsfy0tj|}tj|jr$tj|n tj|Wn0tk r`}z|jtjkrPWYdd}~XnXdS)z>Convenience function for removing temporary test files or dirsN) rlstatS_ISDIRst_modermdirrrrENOENT)rmstrrgrgrhr>s    cCsDytj|Wn0tk r>}z|jtjkr.WYdd}~XnXdS)z-Convenience function for creating a directoryN)rlmkdirrrZEEXIST)dirrrgrgrh safe_mkdirs  rc cs.tj}ztj|dVWdtj|XdS)z@Context manager which temporarily changes the current directory.N)rlrr=)dirnamecurdirrgrgrhr=s   cCstjj| st||rtds*tdt|tr>tj d}t|t sPt|t j dddd}|j |WdQRXztjd|jd |gWdt|jXn.tjt|trtj|}tj||jtjBdS) z1Creates an executable file in the given location.gcczgcc is not installedz #include int main() { pause(); return 1; } z.cFr)suffixrrNz-o)rlrmrsrtrrrrboolrrrrrrrbrcrr>shutilcopyfilerrrchmodrS_IEXEC)ZoutpathZc_coderrrgrgrhr?s$   cCstj||dS)N)rr)rr)rrrgrgrhr@sc@s(eZdZddZeejds$ejjZdS)TestCasecCsd|jj|jj|jfS)Nz%s.%s.%s)rrrZ_testMethodName)rrgrgrh__str__s zTestCase.__str__assertRaisesRegexN) rrrr!runittestr ZassertRaisesRegexpr"rgrgrgrhr s r cCs$dtjkrdtjd<tjjjdS)NZPSUTIL_TESTINGrU)rlr]rpZ _psplatformZcextZ set_testingrgrgrgrh _setup_testss  r$cCs`ddtjtD}dtjkr,dd|D}tj}x&|D]}d|}|jtjj|q:W|S)NcSs<g|]4}|jdr|jdr|jd rtjj|dqS)z.pyZtest_Ztest_memory_leaksr)rrvrlrmsplitext)rxryrgrgrhrzszget_suite..ZWHEELHOUSE_UPLOADER_USERNAMEcSsg|]}|jds|qS)osxposixlinux)r&r'r()r)rxryrgrgrhrzszpsutil.tests.%s) rlrHEREr]r# TestSuiteaddTestdefaultTestLoaderloadTestsFromName)ZtestmodssuiteZtmrgrgrhr; s  cCs8ttjtdjt}|j}tj|r.dnddS)N) verbosityrrY) r$r#TextTestRunnerr$rr; wasSuccessfulrjexit)resultsuccessrgrgrhr<scCshttjjtjj|d}tj}|jtjj |tj t dj |}|j }tj|r^dnddS)Nr)r/rY)r$rlrmr%rr#r*r+r,r-r0r$rr1rjr2)rr.r3r4rgrgrhr:#scCsttd|dS)zZDecorator which runs a test function and retries N times before actually failing. N)rrr)rrt)rrgrgrhr9/scsfdd}|S)z,Decorator to Ignore AccessDenied exceptions.cstjfdd}|S)Nc s>y ||Stjk r8dk r*s*tjdYnXdS)Nzraises AccessDenied)rpZ AccessDeniedr#SkipTest)rr)ronly_ifrgrhr9s z9skip_on_access_denied..decorator..wrapper)rr)rr)r6)rrhr8s z(skip_on_access_denied..decoratorrg)r6rrg)r6rhr76s csfdd}|S)z3Decorator to Ignore NotImplementedError exceptions.cstjfdd}|S)Nc sFy ||Stk r@dk r(s(dj}tj|YnXdS)Nz4%r was skipped because it raised NotImplementedError)rrr#r5)rrmsg)rr6rgrhrIs z;skip_on_not_implemented..decorator..wrapper)rr)rr)r6)rrhrHs z*skip_on_not_implemented..decoratorrg)r6rrg)r6rhr8Fs 127.0.0.1c CsFtjtj.}|jtjtjd|j|df|jdSQRXdS)zReturn an unused TCP port.rYrN)rrr setsockopt SOL_SOCKET SO_REUSEADDRr getsockname)hostrrgrgrhrH]sccsJtjs tt|d}z |VWdytj|Wntk rBYnXXdS)zaA context manager which returns a non-existent file name and tries to delete it on exit. )rN)rprrtr@rlunlinkr)rrmrgrgrhrIes   c Cs||dkr|ttfkrd}tj||}y4|jtjtjd|j||tjkrV|jd|St k rv|j YnXdS)zBinds a generic socket.NrTrrYrX)rTr) rrrr9r:r;rrrrer~)familytypeaddrrrgrgrhrJus    c Csttjs ttjj| s t|tjtj|}y"|j||tj krN|j dWnt k rn|j YnX|S)zBind a UNIX socket.rX) rprrtrlrmrsrr{rrrrer~)rr@rrgrgrhrKs   cCstjtj|t}|j||jd|j}tj|t}y@|j||j}x(|j\}}||krn||fS|j qRWWnt k r|j YnXWdQRXdS)z^Build a pair of TCP sockets connected to each other. Return a (server, client) tuple. rXN) rrrrrrr<connectrr~r)r?rAZllrZcaddrargrgrhrLs      c Cstjs td}}y@t|tjd}|jdtjtjtj}|jd|j|Wn6t k r|dk rr|j |dk r|j YnX||fS)zBuild a pair of UNIX sockets connected to each other through the same UNIX file name. Return a (server, client) tuple. N)r@r) rprrtrKrrZ setblockingr{rBrer~)rZserverZclientrgrgrhrMs   c csg}d}}z|jttjtj|jttjtjtrd|jttjtj|jttjtjtrt rt j }t j }t |\}}t |tjd}x|||fD]}|j|qW|VWdx|D] }|jqW|dk rt||dk rt|XdS)z1Open as many socket families / types as possible.N)r@)appendrJrrrrr rrHAS_CONNECTIONS_UNIXrIrrMrKr~r>)ZsocksZfname1Zfname2s1s2Zs3rrgrgrhrNs,      cCsddl}tr$tr$t|tjs$t||tjkrdd|jdD}t |dksVt|x,|D]$}d|kordkns\t|q\Wtst |}|j |nb|tj krt|t st|tst |}|j|n.|tjkrtjd|dk st|n td |dS) z[Check a net address validity. Supported families are IPv4, IPv6 and MAC addresses. rNcSsg|] }t|qSrg)r)rxryrgrgrhrzsz%check_net_address..r}rz([a-fA-F0-9]{2}[:|\-]?){6}zunknown family %r) ipaddressenumr rIntEnumrtrrrrrZ IPv4AddressrrZ IPv6AddressrpZAF_LINKrmatchrr)rAr?rIZoctsZnumrgrgrhrGs&  $    c(Cst|dkst|t|dk}t|dddk}|d|jksBt|d|jksTt|d|jksft|d|jksxt|d|jkst|d |jkst|r|d|j kst|rn|jdkst|t t d ot rnyt j |j|j|j}Wn>t jtfk r2}z|jdtjkr"WYd d }~Xn.)rWrrr)(rrtrwrMr?r@ZladdrZraddrrrrrr rOerrorrrrZEBADFrrrrr{reprrZ EADDRNOTAVAILrpZ CONN_NONErrr|rtupleZportrrGZiprr)rZhas_pidZhas_fdZdupsockrrrAZvalidsrgrgrhrFsf         ( c CsLyddl}t|dstWn"tk r<ddl}|j|SX|j|SdS)z,Backport of importlib.reload of Python 3.3+.rNreload) importlibr ImportErrorimprS)modulerTrVrgrgrhrOFs  cCstjjtjj|d}tjddkr:ddl}|j||Stjdddkrfddlm }|||j Sddl }|j j ||}|j j|}|jj||SdS)Nrrrr)SourceFileLoader)rr)rlrmr%rrjrorVZ load_sourceZimportlib.machineryrX load_moduleimportlib.utilutilspec_from_file_locationmodule_from_specloader exec_module)rmrrVrXrTspecmodrgrgrhrPSs    cCstj|tdS)zRaise a warning msg.N)warningsrQ UserWarning)r7rgrgrhrQhscCsVt|}|j}t|dks&|dtkr*dSt|dd}t|tsDdStdd|DS)z-Check if object is an instance of namedtuple.rYrF_fieldsNcss|]}t|tkVqdS)N)r@r)rxnrgrgrh vsz is_namedtuple..)r@ __bases__rrRrwrall)rytbrrgrgrhrSms  c #sfdtj|d}fddtjjD}tj|}tj||zt j ||VWdt |XdS)zCtx manager which picks up a random shared CO lib used by this process, copies it in another location and loads it in memory via ctypes. Return the new absolutized path. z.so)rrcs6g|].}tjj|jdkrd|jjkr|jqS)rYpython)rlrmr%lower)rxry)extrgrhrzsz'copyload_shared_lib..N) rrrprqr^randomchoicerrctypesZCDLLr>) dst_prefixdstlibsrrg)rmrhrRzs    c #sddlm}ddlm}dtj|d}fddtjjD}tj |}t j ||d}ztj |}|VWd|dk rtj jj}|jg|_||j}|dkr|t|XdS) zCtx manager which picks up a random shared DLL lib used by this process, copies it in another location and loads it in memory via ctypes. Return the new absolutized, normcased path. r)wintypes)WinErrorz.dll)rrcsPg|]H}tjj|jdjkrdtjj|jjkrd|jjkr|jqS)rYrkZwow64)rlrmr%rlr)rxry)rmrgrhrzsz'copyload_shared_lib..N)rprtrurrrprqr^rnrorrZWinDLLZwindllZkernel32 FreeLibraryZHMODULEZargtypesZ_handler>) rqrtrurrrsrcfilervr rg)rmrhrRs$         )rr)rr)rUrV)rWrri)rZr[)N)F)TF)N)N)N)r8)rTrTr)rx)rZ __future__ratexitrrprrrlrnrrrrrrbrjrrrrrrbrrrrrprrr r Zpsutil._commonr Zpsutil._compatr r rrroZ unittest2r#rrUrJ__all__getenvr!builtin_module_namesrZ WIN_VISTArr]getr"rrrrr$rrmrrnrrrr getfilesystemencodingrlZASCII_FSabspathr__file__rrr)rrqr%r&rEr'r(r)Zmemory_full_infordr1r*r+r,Z HAS_THREADSr-r_r.r/r0rurr devnullrrr#rwobjectr{r|rrrrregisterrrrrrr4r6r5r2rr3rBrArrrDEnvironmentErrorrtrErCr>rcontextmanagerr=r?r@r r$r;r<r:r9r7r8rHrIrJrKrLrMrNrGrFrOrPrQrSrRrgrgrgrh sN                                          0  #%   _:             L  PK!δeoo)__pycache__/__init__.cpython-36.opt-1.pycnu[3 JZL@sdZddlmZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl Z ddlZddlZddlZddlZddlZddlZddlZddlZddlZddl mZddl mZddl mZddl mZddlZddlmZdd lmZdd lmZdd lmZdd l m!Z!dd l"m#Z#ddl"m$Z$ddl"m%Z%ddl"m&Z&ej'dkrjddl(Z)nddl)Z)yddl)m*Z*Wne+k rddl*Z*YnXej'dkrddl,Z,ndZ,ddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;dd?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYgDZ-ej.d"pZdZdkZ/d]ej0kZ1erpdndZ2e3ej4j5d#Z6e3ej4j5dZ7d_Z8dZ9dZ:ej.dbse/rdcndZ;e6se7re8d9Z8e:d9Z:ddZej=j?ej@e<ZAeAdeZBeAe$dfZCejDjEdkZFej=jGej=j>ej=jHeIdidiZJej=j>eJdjZKej=jGej=jHeIZLeMejNdkZOeMedlZPeoze ZQeMejNdmZReMejNdnZSeMejNdoZTdpejNjUjVkZWeMejNdqZXeMejNdrZYeMejNdsZZeMejNdtZ[eMeduZ\e\oej]Z^eMedvZ_eMedwZ`dxdyZaeaZbecejddzZed{d|efeDZgehe d}eiZjehe d~eiZkelZmelZnelZoejpddZqejpddZrGdddejsZtddZueuddd5Zveudd7Zwdd6Zxeudd3ZyeuddZzddd4Z{ddHZ|ddGZ}GdddeiZ~e~ejde:ddddJZe~eefde:dddddKZe~ede:ddddIZddBZddZejddAZdddCZeZdd<Ze8fdd;Zddd9Zddd:ZdddNZejdddOZeedfddPZe jfddQZdddRZddSZejddTZddMZddLZddUZddVZddWZddYZereje.attemptz python%s.%srz"can't find python exe real abspath) rsys executableospathrealpathr version_infopsutilProcessrf ValueError)rirfrgrgrh _get_py_exes  rszr+cCs g|]}|jdrtt|qS)ZSTATUS_) startswithgetattrrp).0xrgrgrh srxAF_UNIXSOCK_SEQPACKETc CstjxbtjtdD]P}t|tr0tt}nt}|j|ry t |Wqt k rft j YqXqWx6t D].}y t |Wqrt k rt j YqrXqrWdS)N.)rcloserllistdirr isinstancerrrtr>re traceback print_exc_testfiles_created)nameprefixrmrgrgrh_cleanup_filess      rcCstdddS)NT) recursive)r3rgrgrgrh_cleanup_procssrc@sHeZdZdZddZddZddZdd Zd d Zd d Z ddZ dS) ThreadTaskz6A thread task which does nothing expect staying alive.cCs&tjj|d|_d|_tj|_dS)NFgMbP?) threadingThread__init___running _intervalZEvent_flag)selfrgrgrhrs zThreadTask.__init__cCs|jj}d||jt|fS)Nz<%s running=%s at %#x>) __class____name__rid)rrrgrgrh__repr__szThreadTask.__repr__cCs |j|S)N)start)rrgrgrh __enter__szThreadTask.__enter__cOs |jdS)N)stop)rargskwargsrgrgrh__exit__szThreadTask.__exit__cCs(|jrtdtjj||jjdS)zStart thread and keep it running until an explicit stop() request. Polls for shutdown every 'timeout' seconds. zalready startedN)rrrrrrrwait)rrgrgrhrs zThreadTask.startcCs,d|_|jjx|jr&tj|jqWdS)NT)rrsettimesleepr)rrgrgrhrun s zThreadTask.runcCs |jstdd|_|jdS)z8Stop thread execution and and waits until it is stopped.zalready stoppedFN)rrrjoin)rrgrgrhrszThreadTask.stopN) r __module__ __qualname____doc__rrrrrrrrgrgrgrhrs rcstjfdd}|S)Nc s,y ||Stk r&tYnXdS)N)rer3)rr)funrgrhwrappers  z _cleanup_on_err..wrapper) functoolswraps)rrrg)rrh_cleanup_on_errsrcKs|jdt|jdt|jdtj|jdtjtrF|jdd|dkrttdt}td |g}t j |f|}t j |t td d d n"t j |f|}t j |t|j|S) a{Creates a python subprocess which does nothing for 60 secs and return it as subprocess.Popen instance. If "cmd" is specified that is used instead of python. By default stdin and stdout are redirected to /dev/null. It also attemps to make sure the process is in a reasonably initialized state. The process is registered for cleanup on reap_children(). stdinr`cwdenv creationflagsiNz:from time import sleep;open(r'%s', 'w').close();sleep(60);z-cT)deleteempty) setdefaultrrlgetcwdr]r r>_TESTFNrrbPopen_subprocesses_startedaddrErDpid)cmdkwdsZpylineZsprocrgrgrhr4)s$       cCstjjtd}tjd|tf}tr4t|dd}nt|}t j |j }t |ddd}tj |t|}tj|t j |}||fS)aCreate a subprocess which creates another one as in: A (us) -> B (child) -> C (grandchild). Return a (child, grandchild) tuple. The 2 processes are fully initialized and will live for 60 secs and are registered for cleanup on reap_children(). 2a import subprocess, os, sys, time s = "import os, time;" s += "f = open('%s', 'w');" s += "f.write(str(os.getpid()));" s += "f.close();" s += "time.sleep(60);" subprocess.Popen(['%s', '-c', s]) time.sleep(60) r)rF)rr)rlrmbasenamertextwrapdedentrr r2rprqrrEremoveint _pids_startedr)Z_TESTFN2ssubpZchild1dataZ child2_pidZchild2rgrgrhr6Js     cstrtjtdnt}tjd|}tjt j t j }|j t |j ||jdt||j\}}zNtj|jgggt t|jd}tj|tj|tfddd|S|jXWdQRXdS) z+Create a zombie process and return its PID.)ra import os, sys, time, socket, contextlib child_pid = os.fork() if child_pid > 0: time.sleep(3000) else: # this is the zombie process s = socket.socket(socket.AF_UNIX) with contextlib.closing(s): s.connect('%s') if sys.version_info < (3, ): pid = str(os.getpid()) else: pid = bytes(str(os.getpid()), 'ascii') s.sendall(pid) rYicsjS)N)Zstatusrg)zprocrgrhsz$create_zombie_proc..zret == psutil.STATUS_ZOMBIEN)rtempfilemktemprrrr contextlibclosingsocketryZ settimeoutrbindlistenr2acceptselectfilenorZrecvrrrprqrCr|)Z unix_filesrcsockconn_Zzpidrg)rrhr5ms"       c Ksr|jdd|jddtjtddd@}tj|j|j||jt t |jgf|}t |j WdQRX|S)zeRun python 'src' code string in a separate interpreter. Returns a subprocess.Popen instance. r`NrawtF)rmoder) rrNamedTemporaryFilerrrrwriteflushr4rrDr)rrfrrgrgrhr2s    cKst|ttfrdnd}tr"|r"dnd}|jd||jdtj|jdtj|jdd|jd |tj|f|}tj ||j \}}|j dkrt ||rt ||jd r|d d }|S)zUrun cmd in a subprocess and return its output. raises RuntimeError on error. TFirshellr`raZuniversal_newlinesr NrY)r~strrr rrbrdrrrZ communicate returncode RuntimeErrorrQendswith)rrrflagspr`rargrgrhshs"        rFc 'Cs*dd}|r"ttjjdd}nt}xtrtj}tj|jy |j Wn0t k r~}z|j t j krnWYdd}~XnX|j r|j j|jr|jjz|jr|jjWdy |jWn0t k r}z|j t jkrWYdd}~XnXXq*WxLtrFtj}ytj|}Wn tjk r8||YqX|j|qW|r&x4|D],}y |j Wntjk r|YnXqTWtj|td\}}x@|D]8}td|y |jWntjk rYnXqWtj|td\}}|r x|D]}td|qWx|D]}||jqWdS) a#Terminate and wait() any subprocess started by this test suite and ensure that no zombies stick around to hog resources and create problems when looking for refleaks. If resursive is True it also tries to terminate and wait() all grandchildren started by this process. c Ss*ytj|}Wntjk r$YnXdS)N)rprq NoSuchProcess)rrrgrgrh assert_gones  z"reap_children..assert_goneT)rN)timeoutz0couldn't terminate process %r; attempting kill()zprocess %r survived kill())rrprqchildrenrpoprrrZ terminateOSErrorerrnoZESRCHr`r|rarrZECHILDrZ wait_procsrrQkill) rrrrerrrrZgonealivergrgrhr3sd                 cCsts tdd}tjd}x(|D] }|js6|dkr@||7}q"Pq"W|sVtd|d}d}|jd}t|d}t|dkrt|d}t|dkrt|d}|||fS) z"Return a tuple such as (2, 6, 36).z not POSIXrTrr{zcan't parse %rrrYr) rNotImplementedErrorrlunameisdigitrrsplitrlen)rrcminormicroZnumsmajorrgrgrhrBs&          cCsdts tdtj}t|dr*|jp&d}n(tjd|d}|rNt|j d}nd}|d|d|fS)Nz not WINDOWSservice_pack_majorrz\s\d$rrY) r rrjZgetwindowsversionhasattrrresearchrgroup)ZwvZsprrgrgrhrA3s  c@s@eZdZdZedddddfddZdd Zd d Zd d ZdS)retryzA retry decorator.NgMbP?cCst|tjdS)N)file)printrjra)rrgrgrhrOszretry.cCs2|r|rtd||_||_||_||_||_dS)Nz/timeout and retries args are mutually exclusive)rr exceptionrretriesintervallogfun)rrrrrrrgrgrhrJszretry.__init__ccs`|jr.tj|j}xFtj|kr*dVqWn.|jrPx&t|jD] }dVq@Wn x dVqRWdS)N)rrrrange)rZstop_atrrgrgrh__iter__Ys  zretry.__iter__cCs|jdk rtj|jdS)N)rrr)rrgrgrhres z retry.sleepcs"tjfdd}|_|S)Ncstd}x^D]V}y ||Sjk r^}z(|}jdk rDj|jw WYdd}~Xq Xq Wtrn|ndS)N)rrrr )rrexcr)rrrgrhrjs    zretry.__call__..wrapper)rr decorator)rrrrg)rrrh__call__iszretry.__call__) rrrrrerrrrrgrgrgrhrGs  rgMbP?)rrrrcCstj|trtjddS)zWait for pid to show up in the process list then return. Used in the test suite to give time the sub process to initialize. g{Gz?N)rprqr rr)rrgrgrhrDs Tc Cs4t|d}|j}WdQRX|s"|r0tj||S)z8Wait for a file to be written on disk with some content.rbN)openreadrlr)ZfnamerrrrrgrgrhrEs   cCs |}|S)zVKeep calling function for timeout secs and exit if eval() expression is True. rg)rexprretrgrgrhrCscCsfy0tj|}tj|jr$tj|n tj|Wn0tk r`}z|jtjkrPWYdd}~XnXdS)z>Convenience function for removing temporary test files or dirsN) rlstatS_ISDIRst_modermdirrrrENOENT)rmstrrgrgrhr>s    cCsDytj|Wn0tk r>}z|jtjkr.WYdd}~XnXdS)z-Convenience function for creating a directoryN)rlmkdirrrZEEXIST)dirrrgrgrh safe_mkdirs  rc cs.tj}ztj|dVWdtj|XdS)z@Context manager which temporarily changes the current directory.N)rlrr=)dirnamecurdirrgrgrhr=s   cCs|rvtdstdt|tr(tjd}tjdddd}|j|WdQRXzt j d|j d |gWdt |j Xn.t jt|trtj|}tj||jtjBdS) z1Creates an executable file in the given location.gcczgcc is not installedz #include int main() { pause(); return 1; } z.cFr)suffixrrNz-o)rrrr~boolrrrrrrbrcrr>shutilcopyfilerrrlr chmodr S_IEXEC)ZoutpathZc_coderrrgrgrhr?s    cCstj||dS)N)rr)rr)rrrgrgrhr@sc@s(eZdZddZeejds$ejjZdS)TestCasecCsd|jj|jj|jfS)Nz%s.%s.%s)rrrZ_testMethodName)rrgrgrh__str__s zTestCase.__str__assertRaisesRegexN) rrrrrunittestrZassertRaisesRegexprrgrgrgrhrs rcCs$dtjkrdtjd<tjjjdS)NZPSUTIL_TESTINGrU)rlr]rpZ _psplatformZcextZ set_testingrgrgrgrh _setup_testss  r cCs`ddtjtD}dtjkr,dd|D}tj}x&|D]}d|}|jtjj|q:W|S)NcSs<g|]4}|jdr|jdr|jd rtjj|dqS)z.pyZtest_Ztest_memory_leaksr)rrtrlrmsplitext)rvrwrgrgrhrxszget_suite..ZWHEELHOUSE_UPLOADER_USERNAMEcSsg|]}|jds|qS)osxposixlinux)r"r#r$)r)rvrwrgrgrhrxszpsutil.tests.%s) rlr}HEREr]r TestSuiteaddTestdefaultTestLoaderloadTestsFromName)ZtestmodssuiteZtmrgrgrhr; s  cCs8ttjtdjt}|j}tj|r.dnddS)N) verbosityrrY) r rTextTestRunnerr$rr; wasSuccessfulrjexit)resultsuccessrgrgrhr<scCshttjjtjj|d}tj}|jtjj |tj t dj |}|j }tj|r^dnddS)Nr)r+rY)r rlrmr!rrr&r'r(r)r,r$rr-rjr.)rr*r/r0rgrgrhr:#scCsttd|dS)zZDecorator which runs a test function and retries N times before actually failing. N)rrr)rAssertionError)rrgrgrhr9/scsfdd}|S)z,Decorator to Ignore AccessDenied exceptions.cstjfdd}|S)Nc s>y ||Stjk r8dk r*s*tjdYnXdS)Nzraises AccessDenied)rpZ AccessDeniedrSkipTest)rr)ronly_ifrgrhr9s z9skip_on_access_denied..decorator..wrapper)rr)rr)r3)rrhr8s z(skip_on_access_denied..decoratorrg)r3rrg)r3rhr76s csfdd}|S)z3Decorator to Ignore NotImplementedError exceptions.cstjfdd}|S)Nc sFy ||Stk r@dk r(s(dj}tj|YnXdS)Nz4%r was skipped because it raised NotImplementedError)rrrr2)rrmsg)rr3rgrhrIs z;skip_on_not_implemented..decorator..wrapper)rr)rr)r3)rrhrHs z*skip_on_not_implemented..decoratorrg)r3rrg)r3rhr8Fs 127.0.0.1c CsFtjtj.}|jtjtjd|j|df|jdSQRXdS)zReturn an unused TCP port.rYrN)rrr setsockopt SOL_SOCKET SO_REUSEADDRr getsockname)hostrrgrgrhrH]sccs@t|d}z |VWdytj|Wntk r8YnXXdS)zaA context manager which returns a non-existent file name and tries to delete it on exit. )rN)r@rlunlinkr)rrmrgrgrhrIes  c Cs||dkr|ttfkrd}tj||}y4|jtjtjd|j||tjkrV|jd|St k rv|j YnXdS)zBinds a generic socket.NrTrrYrX)rTr) rrrr6r7r8rrrrer|)familytypeaddrrrgrgrhrJus    c CsTtjtj|}y"|j||tjkr.|jdWntk rN|jYnX|S)zBind a UNIX socket.rX)rryrrrrer|)rr=rrgrgrhrKs  cCstjtj|t}|j||jd|j}tj|t}y@|j||j}x(|j\}}||krn||fS|j qRWWnt k r|j YnXWdQRXdS)z^Build a pair of TCP sockets connected to each other. Return a (server, client) tuple. rXN) rrrrrrr9connectrr|r)r<r>ZllrZcaddrargrgrhrLs      c Csd}}y@t|tjd}|jdtjtjtj}|jd|j|Wn6tk r~|dk rh|j|dk rx|jYnX||fS)zBuild a pair of UNIX sockets connected to each other through the same UNIX file name. Return a (server, client) tuple. N)r=r)rKrrZ setblockingryr?rer|)rZserverZclientrgrgrhrMs  c csg}d}}z|jttjtj|jttjtjtrd|jttjtj|jttjtjtrt rt j }t j }t |\}}t |tjd}x|||fD]}|j|qW|VWdx|D] }|jqW|dk rt||dk rt|XdS)z1Open as many socket families / types as possible.N)r=)appendrJrrrrr rrHAS_CONNECTIONS_UNIXrIrrMrKr|r>)ZsocksZfname1Zfname2s1s2Zs3rrgrgrhrNs,      cCsddl}trtr|tjkrTdd|jdD}x |D]}q4WtsHt|}|j|n8|tjkrvtsjt|}|j |n|t j krn t d|dS)z[Check a net address validity. Supported families are IPv4, IPv6 and MAC addresses. rNcSsg|] }t|qSrg)r)rvrwrgrgrhrxsz%check_net_address..r{zunknown family %r) ipaddressenumr rrrrZ IPv4AddressrZ IPv6AddressrpZAF_LINKrr)r>r<rEZoctsZnumrgrgrhrGs       c(Cst|dk}t|dd d k}|r |rttdrt rytj|j|j|j}Wn:tj t fk r}z|j dt j krvWYdd}~XnXtj|WdQRX|jttfkr2|jtkr>tj|j|j}tj|Vy|j|jddfWn6tj k r$}z|j t jkrWYdd}~XnXWdQRXn |jtkr>|jtkrJxL|j|jfD]<}|jttfkr|svqXt|j|jn |jtkrXqXWddttD}dS) z*Check validity of a connection namedtuple.rfdrYfromfdrNcSs g|]}|jdrtt|qS)ZCONN_)rtrurp)rvrwrgrgrhrx=sz+check_connection_ntuple..rr)rrurrr rHrGr<r=errorrrrZEBADFrrrrrZladdrZ EADDRNOTAVAILryrZraddrrGZiprrp)rZhas_pidZhas_fdZdupsockrrr>ZvalidsrgrgrhrFs@         c CsLyddl}t|dstWn"tk r<ddl}|j|SX|j|SdS)z,Backport of importlib.reload of Python 3.3+.rNreload) importlibr ImportErrorimprJ)modulerKrMrgrgrhrOFs  cCstjjtjj|d}tjddkr:ddl}|j||Stjdddkrfddlm }|||j Sddl }|j j ||}|j j|}|jj||SdS)Nrrrr)SourceFileLoader)rr)rlrmr!rrjrorMZ load_sourceZimportlib.machineryrO load_moduleimportlib.utilutilspec_from_file_locationmodule_from_specloader exec_module)rmrrMrOrKspecmodrgrgrhrPSs    cCstj|tdS)zRaise a warning msg.N)warningsrQ UserWarning)r4rgrgrhrQhscCsVt|}|j}t|dks&|dtkr*dSt|dd}t|tsDdStdd|DS)z-Check if object is an instance of namedtuple.rYrF_fieldsNcss|]}t|tkVqdS)N)r=r)rvnrgrgrh vsz is_namedtuple..)r= __bases__rtuplerur~all)rwtbrrgrgrhrSms  c #sfdtj|d}fddtjjD}tj|}tj||zt j ||VWdt |XdS)zCtx manager which picks up a random shared CO lib used by this process, copies it in another location and loads it in memory via ctypes. Return the new absolutized path. z.so)rrcs6g|].}tjj|jdkrd|jjkr|jqS)rYpython)rlrmr!lower)rvrw)extrgrhrxsz'copyload_shared_lib..N) rrrprqr^randomchoicerrctypesZCDLLr>) dst_prefixdstlibsrrg)rerhrRzs    c #sddlm}ddlm}dtj|d}fddtjjD}tj |}t j ||d}ztj |}|VWd|dk rtj jj}|jg|_||j}|dkr|t|XdS) zCtx manager which picks up a random shared DLL lib used by this process, copies it in another location and loads it in memory via ctypes. Return the new absolutized, normcased path. r)wintypes)WinErrorz.dll)rrcsPg|]H}tjj|jdjkrdtjj|jjkrd|jjkr|jqS)rYrcZwow64)rlrmr!rdr)rvrw)rergrhrxsz'copyload_shared_lib..N)rhrlrmrrrprqr^rfrgrrZWinDLLZwindllZkernel32 FreeLibraryZHMODULEZargtypesZ_handler>) rirlrmrjrkrcfilernr rg)rerhrRs$         )rr)rr)rUrV)rWrri)rZr[)N)F)TF)N)N)N)r5)rTrTr)rp)rZ __future__ratexitrrhrrrlrfrrrrr rbrjrrrrrrYrrrrrprrr r Zpsutil._commonr Zpsutil._compatr r rrroZ unittest2rrrLrF__all__getenvr!builtin_module_namesrZ WIN_VISTArr]getr"rrrrr$rrmrrnrrrr getfilesystemencodingrdZASCII_FSabspathr__file__rrr%rrqr%r&rBr'r(r)Zmemory_full_infor[r1r*r+r,Z HAS_THREADSr-r_r.r/r0rsrrdevnullrrr#ruobjectryrzrrrrregisterrrrrrr4r6r5r2rr3rBrArrrDEnvironmentErrorr1rErCr>rcontextmanagerr=r?r@rr r;r<r:r9r7r8rHrIrJrKrLrMrNrGrFrOrPrQrSrRrgrgrgrh sN                                          0  #%   _:             L  PK!V% )__pycache__/test_aix.cpython-36.opt-1.pycnu[3 JZm@sxdZddlZddlmZddlmZddlmZddlmZddlZeje dGdd d ej Z e d krtee dS) zAIX specific tests.N)AIX)run_test_module_by_name)sh)unittestzAIX onlyc@s4eZdZddZddZddZddZd d Zd S) AIXSpecificTestCasec Cstd}d}xdjD]}|d|f7}qWtj||}|j|dd}t|jd|}t|jd|}t|jd |}t|jd |} tj} d ||} |j | j ||j | j || d |j | j || d |j | j| | d dS) Nz/usr/bin/svmon -O unit=KBz memory\s*z+size inuse free pin virtual available mmodez(?P<%s>\S+)\s+z(svmon command returned unexpected outputisize availableZinusefree)delta)rsplitresearchassertIsNotNoneintgrouppsutilZvirtual_memory assertEqualtotalassertAlmostEqualusedrr ) selfout re_patternfieldmatchobjZKBrrrr psutil_resultZMEMORY_TOLERANCEr /usr/lib64/python3.6/test_aix.pytest_virtual_memorys*  z'AIXSpecificTestCase.test_virtual_memorycCsTtd}tjd|}|j|dt|jd}d}tj}|jt|j ||dS)Nz/usr/sbin/lsps -az=(?P\S+)\s+(?P\S+)\s+(?P\S+)\s+(?P\d+)MBz'lsps command returned unexpected outputrir i) rr rrrrrZ swap_memoryrr)rrrZtotal_mbZMBrrrrtest_swap_memory4sz$AIXSpecificTestCase.test_swap_memorycCstd}d}xdjD]}|d|f7}qWtj||}|j|dd}tj}|j|jt |j d|d|j|j t |j d |d|j|j t |j d |d|j|j t |j d |ddS) Nz/usr/bin/mpstat -azALL\s*zfmin maj mpcs mpcr dev soft dec ph cs ics bound rq push S3pull S3grd S0rd S1rd S2rd S3rd S4rd S5rd syscz(?P<%s>\S+)\s+z)mpstat command returned unexpected outputiZcs)r ZsyscZdevZsoft)rr r rrrZ cpu_statsrZ ctx_switchesrrZsyscallsZ interruptsZsoft_interrupts)rrrrrZCPU_STATS_TOLERANCErrrrtest_cpu_statsIs2     z"AIXSpecificTestCase.test_cpu_statscCs:td}ttjd|jd}tjdd}|j||dS)Nz/usr/bin/mpstat -az lcpu=(\d+)T)Zlogical)rrr rrr cpu_countr)rrZ mpstat_lcpuZ psutil_lcpurrrtest_cpu_count_logicaljs z*AIXSpecificTestCase.test_cpu_count_logicalcCs4td}t|j}ttjj}|j||dS)Nz/etc/ifconfig -l)rsetr rZ net_if_addrskeysZassertSetEqual)rrZifconfig_namesZ psutil_namesrrrtest_net_if_addrs_namesps z+AIXSpecificTestCase.test_net_if_addrs_namesN)__name__ __module__ __qualname__rr r!r$r'rrrrrs !r__main__) __doc__r rrZ psutil.testsrrrZskipIfZTestCaserr(__file__rrrrs     cPK! &%__pycache__/test_sunos.cpython-36.pycnu[3 JZ@sxdZddlZddlZddlmZddlmZddlmZddlmZeje dGdd d ej Z e d krtee dS) zSun OS specific tests.N)SUNOS)run_test_module_by_name)sh)unittestz SUNOS onlyc@seZdZddZddZdS)SunOSSpecificTestCasec Cstdtjd}|jjddd}|s4tdd}}xL|D]D}|j}|d d\}}|tt|d7}|tt|d7}qBW||}tj} |j | j ||j | j ||j | j |dS) Nz#env PATH=/usr/sbin:/sbin:%s swap -lPATH zno swap device(s) configuredri) rosenvironstripsplit ValueErrorintpsutilZ swap_memory assertEqualtotalusedfree) selfoutlinesrrlinetfrZ psutil_swapr"/usr/lib64/python3.6/test_sunos.pytest_swap_memorys z&SunOSSpecificTestCase.test_swap_memorycCs&td}|jtjt|jddS)Nz/usr/sbin/psrinfor)rrr cpu_countlenr)rrrrrtest_cpu_count&sz$SunOSSpecificTestCase.test_cpu_countN)__name__ __module__ __qualname__rr"rrrrrsr__main__) __doc__r rrZ psutil.testsrrrZskipIfZTestCaserr#__file__rrrrs     PK!Z)*)*)__pycache__/test_osx.cpython-36.opt-1.pycnu[3 JZ%@s<dZddlZddlZddlZddlZddlmZddlmZddlmZddlm Z ddlm Z ddlm Z dd lm Z dd lm Z dd lmZdd lmZerejd ndZddZddZddZeje dGdddejZeje dGdddejZeje dGdddejZedkr8e edS)zOSX specific tests.N)OSX)create_zombie_proc)get_test_subprocess) HAS_BATTERY)MEMORY_TOLERANCE) reap_children)retry_before_failing)run_test_module_by_name)sh)unittest SC_PAGE_SIZEc Cs6t|}|jd}yt|Stk r0|SXdS)zmExpects a sysctl command with an argument and parse the result returning only the value of interest. N)r splitint ValueError)cmdlineoutresultr /usr/lib64/python3.6/test_osx.pysysctls  rcCsHtd}x$|jdD]}||krPqWtdttjd|jdtS)z)Wrapper around 'vm_stat' cmdline utility.vm_stat zline not foundz\d+r)r rrrresearchgroupPAGESIZE)Zfieldrlinerrrr(s rc Csddi}|}d }x@|r&|d d js6|d d dkrP||d 7}|d d}qWt|}|j}xD|jD]\}}||krlPqlW|dkr|d}|j}n td||d d i}x0t|d dD]\}}d |d d>||<qWt|||S)NZ customaryBKMGTPEZYrr .kzcan't interpret %r ) rrr r!r"r#r$r%r&)isdigitfloatstripitemsupperr enumerater) sZSYMBOLSZinitnumZletternameZssetprefixirrr human2bytes4s&&    r6zOSX onlyc@s,eZdZeddZeddZddZdS) TestProcesscCstj|_dS)N)rpid)clsrrr setUpClassQszTestProcess.setUpClasscCs tdS)N)r)r9rrr tearDownClassUszTestProcess.tearDownClasscCstd|j}|jddj}|jdd }|jdd }tj|jj}|j|t j dt j ||j|t j dt j |dS) Nzps -o lstart -p %sZSTARTEDr' r z%H:%M:%Sz%Y) r r8replacer-rpsutilProcess create_time assertEqualtimeZstrftimeZ localtime)selfoutputZstart_psZhhmmssZyearZ start_psutilrrrtest_process_create_timeYsz$TestProcess.test_process_create_timeN)__name__ __module__ __qualname__ classmethodr:r;rHrrrrr7Ns  r7c@seZdZeddZeddZddZddZd d Zd d Z d dZ ddZ ddZ ddZ ddZddZddZddZddZdd Zd!S)"TestZombieProcessAPIscCst}tj||_dS)N)rrArBp)r9Zzpidrrrr:jsz TestZombieProcessAPIs.setUpClasscCstdddS)NT) recursive)r)r9rrrr;osz#TestZombieProcessAPIs.tearDownClasscCsJ|j|jjtj|jj|jj|jj|jj|jj dS)N) rDrNZstatusrAZ STATUS_ZOMBIEZppidZuidsZgidsZterminalrC)rFrrrtest_pidtask_infoss     z'TestZombieProcessAPIs.test_pidtask_infocCs|jtj|jjdS)N) assertRaisesrA ZombieProcessrNZexe)rFrrrtest_exe{szTestZombieProcessAPIs.test_execCs|jtj|jjdS)N)rQrArRrNr)rFrrr test_cmdline~sz"TestZombieProcessAPIs.test_cmdlinecCs|jtj|jjdS)N)rQrArRrNenviron)rFrrr test_environsz"TestZombieProcessAPIs.test_environcCs|jtj|jjdS)N)rQrArRrNcwd)rFrrrtest_cwdszTestZombieProcessAPIs.test_cwdcCs|jtj|jjdS)N)rQrArRrNZmemory_full_info)rFrrrtest_memory_full_infosz+TestZombieProcessAPIs.test_memory_full_infocCs|jtj|jjdS)N)rQrArRrNZ cpu_times)rFrrrtest_cpu_timessz$TestZombieProcessAPIs.test_cpu_timescCs|jtj|jjdS)N)rQrArRrNZnum_ctx_switches)rFrrrtest_num_ctx_switchessz+TestZombieProcessAPIs.test_num_ctx_switchescCs|jtj|jjdS)N)rQrArRrNZ num_threads)rFrrrtest_num_threadssz&TestZombieProcessAPIs.test_num_threadscCs|jtj|jjdS)N)rQrArRrNZ open_files)rFrrrtest_open_filessz%TestZombieProcessAPIs.test_open_filescCs|jtj|jjdS)N)rQrArRrNZ connections)rFrrrtest_connectionssz&TestZombieProcessAPIs.test_connectionscCs|jtj|jjdS)N)rQrArRrNZnum_fds)rFrrr test_num_fdssz"TestZombieProcessAPIs.test_num_fdscCs|jtjtjf|jjdS)N)rQrArRZ AccessDeniedrNZthreads)rFrrr test_threadssz"TestZombieProcessAPIs.test_threadscCs|jtj|jjdS)N)rQrArRrNZ memory_maps)rFrrrtest_memory_mapssz&TestZombieProcessAPIs.test_memory_mapsN)rIrJrKrLr:r;rPrSrTrVrXrYrZr[r\r]r^r_r`rarrrrrMgs   rMc@seZdZddZddZddZddZd d Zed d Z ed dZ eddZ eddZ eddZ eddZeddZddZeje dddZdS)TestSystemAPIscCsdd}xtjddD]}tj|j}||j\}}}}|j|j||j|j|t|j|d krx|j d|j|t|j |d kr|j d|j |qWdS) NcSstd|j}|jd}|jd|jd}|jdd\}}}}|dkrRd}t|d}t|d}t|d}||||fS)Nz df -k "%s"rrZnoner'i)r r-rpopr)pathrlinesrdevtotalusedfreerrrdfs      z%TestSystemAPIs.test_disks..dfF)allr*izpsutil=%s, df=%si(ii(i) rAZdisk_partitionsZ disk_usageZ mountpointrDZdevicerhabsrjZfailri)rFrkpartZusagergrhrirjrrr test_diskss  zTestSystemAPIs.test_diskscCs td}|j|tjdddS)Nzsysctl hw.logicalcpuT)logical)rrDrA cpu_count)rFr2rrrtest_cpu_count_logicalsz%TestSystemAPIs.test_cpu_count_logicalcCs td}|j|tjdddS)Nzsysctl hw.physicalcpuF)rp)rrDrArq)rFr2rrrtest_cpu_count_physicalsz&TestSystemAPIs.test_cpu_count_physicalcCsZtj}|j|jddtd|j|jddtd|j|jddtddS)Nizsysctl hw.cpufrequencyzsysctl hw.cpufrequency_minzsysctl hw.cpufrequency_max)rAZcpu_freqrDZcurrentrminmax)rFZfreqrrr test_cpu_freqszTestSystemAPIs.test_cpu_freqcCstd}|j|tjjdS)Nzsysctl hw.memsize)rrDrAvirtual_memoryrh)rFZsysctl_hwphymemrrrtest_vmem_totalszTestSystemAPIs.test_vmem_totalcCs&td}tjj}|j||tddS)Nrj)delta)rrArwrjassertAlmostEqualr)rF vmstat_val psutil_valrrrtest_vmem_frees zTestSystemAPIs.test_vmem_freecCs.tdtd}tjj}|j||tddS)Ninactiverj)ry)rrArwZ availablerzr)rFr{r|rrrtest_vmem_availables z"TestSystemAPIs.test_vmem_availablecCs&td}tjj}|j||tddS)Nactive)ry)rrArwrrzr)rFr{r|rrrtest_vmem_actives zTestSystemAPIs.test_vmem_activecCs&td}tjj}|j||tddS)Nr~)ry)rrArwr~rzr)rFr{r|rrrtest_vmem_inactives z!TestSystemAPIs.test_vmem_inactivecCs&td}tjj}|j||tddS)Nwired)ry)rrArwrrzr)rFr{r|rrrtest_vmem_wireds zTestSystemAPIs.test_vmem_wiredcCs"td}tjj}|j||dS)NZPageins)rrA swap_memoryZsinrD)rFr{r|rrrtest_swapmem_sins zTestSystemAPIs.test_swapmem_sincCs"td}tjj}|j||dS)NZPageout)rrArZsoutrD)rFr{r|rrrtest_swapmem_souts z TestSystemAPIs.test_swapmem_soutcCsxxrtjjD]b\}}ytd|}Wntk r:YqX|j|jd|k|d|j|jtt j d|dqWdS)Nz ifconfig %sZRUNNING)msgz mtu (\d+)r) rAZ net_if_statsr.r RuntimeErrorrDZisupZmturrfindall)rFr3Zstatsrrrrtest_net_if_statssz TestSystemAPIs.test_net_if_statsz no batterycCs`td}tjd|jd}tjd|jd}|dk}tj}|j|j||j|jt |dS)Nz pmset -g battz(\d+)%r zNow drawing from '([^']+)'zAC Power) r rrrrAZsensors_batteryrD power_pluggedpercentr)rFrrZ drawing_fromrZ psutil_resultrrrtest_sensors_battery"sz#TestSystemAPIs.test_sensors_batteryN)rIrJrKrorrrsrvrxrr}rrrrrrrr skipIfrrrrrrrbs  rb__main__)__doc__osrrErArZ psutil.testsrrrrrrr r r sysconfrrrr6rZTestCaser7rMrbrI__file__rrrrs6              <  PK!j::+__pycache__/test_connections.cpython-36.pycnu[3 JZP@s8dZddlZddlZddlZddlmZddlmZddlmZddlmZddlm Z ddl Z ddl m Z dd l m Z dd l m Z dd l mZdd l mZdd l mZddl mZddl mZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddlm$Z$ddlm%Z%dd lm&Z&dd!lm'Z'dd"lm(Z(dd#lm)Z)dd$lm*Z*e j+Z,Gd%d&d&e-Z.Gd'd(d(e.e'j/Z0Gd)d*d*e.e'j/Z1Gd+d,d,e.e'j/Z2Gd-d.d.e'j/Z3e4d/kr4e!e5dS)0z;Tests for net_connections() and Process.connections() APIs.N)closing)AF_INET)AF_INET6) SOCK_DGRAM) SOCK_STREAM)FREEBSD)LINUX)NETBSD)OPENBSD)OSX)POSIX)SUNOS)WINDOWS) supports_ipv6)PY3)AF_UNIX) bind_socket)bind_unix_socket)check_connection_ntuple)create_sockets) get_free_port)HAS_CONNECTIONS_UNIX)pyrun) reap_children)run_test_module_by_name) safe_rmpath)skip_on_access_denied)tcp_socketpair)TESTFN)TRAVIS)unittest)unix_socket_path)unix_socketpair) wait_for_filec@s8eZdZddZddZddZd dd Zdd d ZdS)BasecCs"tstjdd}| st|dS)Nall)kind)r thisproc connectionsAssertionError)selfconsr,(/usr/lib64/python3.6/test_connections.pysetUp6s z Base.setUpcCs0tttts,tjdd}| s,t|dS)Nr%)r&)rrrr r'r(r))r*r+r,r,r-tearDown<s  z Base.tearDowncCsrtjdd}tdd|D}tr.||jS|jt|d|djdkrf|j||jj|j|dSdS)Nr%)r&cSsg|]}|j|fqSr,)fd).0cr,r,r- Gsz+Base.get_conn_from_sock..r)r'r(dictr fileno assertEquallenr0)r*sockr+Zsmapr,r,r-get_conn_from_sockEs  zBase.get_conn_from_sockNcCs|dkr|j|}t||jdkr6|j|j|j|j|j|j|j|j|jtj tj |j }| rt rt |tr|j}|jtkr|dd}|jtkrtrn|j|j||jtkrtrtjdd}|jtj||S)zGiven a socket, makes sure it matches the one obtained via psutil. It assumes this process created one connection only (the one supposed to be checked). Nr4r%)r&r5)r;rr0r8r7familytypeZ getsockoptsocketZ SOL_SOCKETZSO_TYPEZ getsocknamer isinstancebytesdecoderrr laddrrr'r(compare_procsys_connectionsosgetpid)r*r:connrCr+r,r,r- check_socketRs(     zBase.check_socketr%c sdytj|d}Wn tjk r0tr*dSYnXfdd|D}|j|j|j||dS)zGiven a process PID and its list of connections compare those against system-wide connections retrieved via psutil.net_connections. )r&Ncs"g|]}|jkr|ddqS)Nr4r5)pid)r1r2)rIr,r-r3sz4Base.compare_procsys_connections..)psutilnet_connectionsZ AccessDeniedr sortr8)r*rIZ proc_consr&Zsys_consr,)rIr-rDvsz Base.compare_procsys_connections)N)r%)__name__ __module__ __qualname__r.r/r;rHrDr,r,r,r-r$4s   $r$c@s|eZdZdZddZeje dddZddZ eje dd d Z eje d d d Z eje d ddZ dS)TestUnconnectedSocketsz;Tests sockets which are open but not connected to anything.c CsRdtf}tttt|d,}|j|}|j s4t|j|j t j WdQRXdS)Nz 127.0.0.1)addr) rrrrrrHraddrr)r8statusrJ CONN_LISTEN)r*rQr:rGr,r,r- test_tcp_v4s    z"TestUnconnectedSockets.test_tcp_v4zIPv6 not supportedc CsRdtf}tttt|d,}|j|}|j s4t|j|j t j WdQRXdS)Nz::1)rQ) rrrrrrHrRr)r8rSrJrT)r*rQr:rGr,r,r- test_tcp_v6s    z"TestUnconnectedSockets.test_tcp_v6c CsRdtf}tttt|d,}|j|}|j s4t|j|j t j WdQRXdS)Nz 127.0.0.1)rQ) rrrrrrHrRr)r8rSrJ CONN_NONE)r*rQr:rGr,r,r- test_udp_v4s    z"TestUnconnectedSockets.test_udp_v4c CsRdtf}tttt|d,}|j|}|j s4t|j|j t j WdQRXdS)Nz::1)rQ) rrrrrrHrRr)r8rSrJrW)r*rQr:rGr,r,r- test_udp_v6s    z"TestUnconnectedSockets.test_udp_v6z POSIX onlycCsXtH}tt|td,}|j|}|j s0t|j|jt j WdQRXWdQRXdS)N)r>) r!rrrrHrRr)r8rSrJrW)r*namer:rGr,r,r- test_unix_tcps   z$TestUnconnectedSockets.test_unix_tcpcCsXtH}tt|td,}|j|}|j s0t|j|jt j WdQRXWdQRXdS)N)r>) r!rrrrHrRr)r8rSrJrW)r*rZr:rGr,r,r- test_unix_udps   z$TestUnconnectedSockets.test_unix_udpN)rMrNrO__doc__rUr skipIfrrVrXrYr r[r\r,r,r,r-rPsrPc@sTeZdZdZejedddZeje dddZ e e dd d Z d d Z d S)TestConnectedSocketPairszJTest socket pairs which are are actually connected to each other. zunreliable on SUONSc Csdtf}tjdd sttt|d\}}zHtjdd}|jt|d|j|djt j |j|djt j Wd|j |j XdS)Nz 127.0.0.1tcp4)r&)rQr<rr4) rr'r(r)rrr8r9rSrJZCONN_ESTABLISHEDclose)r*rQserverclientr+r,r,r-test_tcps  z!TestConnectedSocketPairs.test_tcpz POSIX onlycCsltZ}t|\}}z2tjdd}|djo8|dj s@t|djoR|dj sZttrldd|D}|jt |dt st st r|j|djd|j|djd|j||djp|djn~t r xv|dj|dj|dj|djfD]}|j|dqWn<|j|djp$|dj||j|djpB|dj|Wd|j|jXWdQRXdS) Nunix)r&rr4cSsg|]}|jdkr|qS)z /var/run/log)rR)r1r2r,r,r-r3sz6TestConnectedSocketPairs.test_unix..r<)r!r"r'r(rCrRr)r r8r9rrr r ra)r*rZrbrcr+rQr,r,r- test_unixs*    "z"TestConnectedSocketPairs.test_unix)Zonly_ifcsfdd}tjd}tjd}ddlm}tjjt}||jt t d|d}||jt t d|d}||jt t d |d}||jt t d |d} t |} t t|} t |} t t|} trt |}t t|}t | }t t|}nd}d}d}d}xtjD]}|j}jt|d x|D]}|j| jkr\|||t t| ftjdn|j| jkr|||t t| ftjdnZ|jt|ddkr|||t t|ftjdn,|jt|ddkr0|||t t|ftjdq0Wq Wjt|jdddS)Nc sd }t|j|j|j|j|j|j|j|j|j|j|x8|D]0} |j| d } | |krz| stqX| sXt| qXWt rj |j |gdS) Nr%inetinet4inet6tcpr`tcp6udpudp4udp6)r&) r%rhrirjrkr`rlrmrnro) rr8r=r>rCrRrSr(r)rrDrI) procrGr=r>rCrRrSZkindsZ all_kindsr&r+)r*r,r- check_conns   z8TestConnectedSocketPairs.test_combos..check_conna import socket, time s = socket.socket($family, socket.SOCK_STREAM) s.bind(('$addr', 0)) s.listen(1) with open('$testfn', 'w') as f: f.write(str(s.getsockname()[:2])) time.sleep(60) z import socket, time s = socket.socket($family, socket.SOCK_DGRAM) s.bind(('$addr', 0)) with open('$testfn', 'w') as f: f.write(str(s.getsockname()[:2])) time.sleep(60) r)Templatez 127.0.0.1)r=rQZtestfnz::1r4r%rhrirkr`rmrnrIrjrlroz???)r&)r%rhrirkr`)r%rhrirmrn)r%rhrjrkrl)r%rhrjrmro)textwrapdedentstringrrrEpathbasenamerZ substituteintrrrevalr#rr'Zchildrenr(r8r9rIrrJrTrrWgetattr assertRaises ValueError)r*rqZ tcp_templateZ udp_templaterrZtestfileZ tcp4_templateZ udp4_templateZ tcp6_templateZ udp6_templateZ tcp4_procZ tcp4_addrZ udp4_procZ udp4_addrZ tcp6_procZ tcp6_addrZ udp6_procZ udp6_addrpr+rGr,)r*r- test_combossb       z$TestConnectedSocketPairs.test_combosc Cst}tjdd}|jt|t|tjdd}|jt|trJdndx,|D]$}|j|jtt f|j|j t qVWtjdd}|jt|d|j|djt|j|dj t trtjdd}|jt|d|j|djt |j|dj t tjd d}|jt|tr(dndx.|D]&}|j|jtt f|j|j t q4Wtjd d}|jt|d|j|djt|j|dj t trtjd d}|jt|d|j|djt |j|dj t tjd d}|jt|trd ndx2|D]*}|j|jtt f|j|j t t fqWtrtjdd}|jt|dx.|D]&}|j|jt |j|j t t fqlWt rtjdd}|jt|dx.|D]&}|j|jt|j|j t t fqWWdQRXdS)Nr%)r&rkr<r4r`rrlrmrnrorhrjre)rr'r(r8r9rassertInr=rrr>rrrr)r*socksr+rGr,r,r-test_multi_sockets_filteringes`                z5TestConnectedSocketPairs.test_multi_sockets_filteringN)rMrNrOr]r r^r rdr rgrr r~rr,r,r,r-r_s !br_c@sJeZdZdZeddZeddZeeje o6e dddZ d S) TestSystemWideConnectionszTests for net_connections().c sfdd}tddlm}xZ|jD]N\}}|dkrBt rBq*|\}}tj|}jt|tt |||||q*Wj t tjddWdQRXdS)NcsVttdt}xB|D]:}j|j||d|j|krFj|j||dt|qWdS)Nr)msg)rzr?objectrr=r>r)r+familiestypes_rrG)r*r,r-checks   z0TestSystemWideConnections.test_it..checkr) conn_tmaprez???)r&) rpsutil._commonritemsrrJrKr8r9setr{r|)r*rrr&groupsrrr+r,)r*r-test_its   z!TestSystemWideConnections.test_itc Cs@t0}ddtjddD}|jt|t|WdQRXdS)NcSsg|]}|jtjkr|qSr,)rIrErF)r1xr,r,r-r3sz>TestSystemWideConnections.test_multi_socks..r%)r&)rrJrKr8r9)r*rr+r,r,r-test_multi_sockssz*TestSystemWideConnections.test_multi_sockszunreliable on OSX + TRAVISc st}t|}WdQRXgd}xRt|D]F}tjjtt|}tj d|}t |}j |j |j t|q,Wx$t|D]}tt|}t|qWfddtjddD}xJD]B|jtfdd|D|tj} |jt| jd|qWdS)N a import time, os from psutil.tests import create_sockets with create_sockets(): with open('%s', 'w') as f: f.write(str(os.getpid())) time.sleep(60) csg|]}|jkr|qSr,)rI)r1r)pidsr,r-r3szFTestSystemWideConnections.test_multi_sockets_procs..r%)r&csg|]}|jkr|qSr,)rI)r1r)rIr,r-r3s)rr9rangerErvrealpathrstrrsrtrappendrIZ addCleanuprr#rJrKr8Processr() r*rZexpectedtimesiZfnamesrcZsprocZsysconsr}r,)rIrr-test_multi_sockets_procss(       z2TestSystemWideConnections.test_multi_sockets_procsN) rMrNrOr]rrrr r^r rrr,r,r,r-rs rc@seZdZddZdS)TestMisccCsg}g}xhttD]\}|jdrtt|}t|}|jsBt||jt||j|||j||j|qWt rtj tj t rtj dS)NZCONN_)dirrJ startswithrzrisupperr)Z assertNotInrr Z CONN_IDLEZ CONN_BOUNDrZCONN_DELETE_TCB)r*ZintsZstrsrZZnumZstr_r,r,r-test_connection_constantss      z"TestMisc.test_connection_constantsN)rMrNrOrr,r,r,r-rsr__main__)6r]rEr?rs contextlibrrrrrrJrrr r r r r rrrZpsutil._compatrZ psutil.testsrrrrrrrrrrrrrrrr r!r"r#rr'rr$ZTestCaserPr_rrrM__file__r,r,r,r-s^                                  \7`P PK!-__pycache__/test_process.cpython-36.opt-1.pycnu[3 JZ9@sdZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl Z ddlZddlmZddlmZddlmZddlmZddlmZddlmZdd lmZdd lmZdd lmZdd lmZdd lmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddlm$Z$ddlm%Z%ddlm&Z&ddlm'Z'ddlm(Z(ddlm)Z)ddlm*Z*ddlm+Z+ddlm,Z,ddlm-Z-dd lm.Z.dd!lm/Z/dd"lm0Z0dd#lm1Z1dd$lm2Z2dd%lm3Z3dd&lm4Z4dd'lm5Z5dd(lm6Z6dd)lm7Z7dd*lm8Z8dd+lm9Z9dd,lm:Z:dd-lm;Z;dd.lmZ?erej@dkrGd2d3d3e?ZAGd4d5d5e;j>ZBeCd6kre2eDdS)7zTests for psutil.Process class.N)AIX)BSD)LINUX)NETBSD)OPENBSD)OSX)POSIX)SUNOS)WINDOWS)long)PY3)APPVEYOR) call_until)copyload_shared_lib) create_exe)create_proc_children_pair)create_zombie_proc)enum)get_test_subprocess) get_winver)HAS_CPU_AFFINITY) HAS_ENVIRON) HAS_IONICE)HAS_MEMORY_MAPS)HAS_PROC_CPU_NUM)HAS_PROC_IO_COUNTERS) HAS_RLIMIT) HAS_THREADS)mock)PYPY) PYTHON_EXE) reap_children)retry_before_failing)run_test_module_by_name) safe_rmpath)sh)skip_on_access_denied)skip_on_not_implemented)TESTFILE_PREFIX)TESTFN) ThreadTask)TRAVIS)unittest) wait_for_pid) WIN_VISTAc@sreZdZdZddZddZddZdd Zd d Zd d Z ddZ ddZ ddZ ddZ ddZddZddZeje dddZdd Zeje d!ejed"d#d$Zeje deed%d&d'Zeje dejeoee kdd(d)Z!eje dejeoee kdd*d+Z"eje# dd,d-Z$eje# dd.d/Z%eje# dd0d1Z&eje# dd2d3Z'eje# dd4d5Z(d6d7Z)eje d8d9d:Z*eje+ dd;d<Z,e-e.e/d%eje+ dd=d>Z0d?d@Z1dAdBZ2eje3 ddCdDZ4eje3 ddEdFZ5dGdHZ6dIdJZ7dKdLZ8dMdNZ9dOdPZ:eje;dQejeeje d!dWdXZ?dYdZZ@d[d\ZAd]d^ZBd_d`ZCdadbZDejeE ddcddZFejeE ddedfZGejeE ddgdhZHejeIdiejeJdjdkdlZKejeIdiejeJdjdmdnZLeje d!dodpZMeed%ejeNpzeOdqdrdsZPdtduZQdvdwZRdxdyZSdzd{ZTd|d}ZUd~dZVddZWddZXddZYddZZddZ[ddZ\eje d!ddZ]eje d!ddZ^eje d!ddZ_ddZ`ejea dddZbejea deje d!ddZcdS) TestProcesszTests for psutil.Process class.cCs ttdS)N)r$r))selfr1$/usr/lib64/python3.6/test_process.pysetUpNszTestProcess.setUpcCs tdS)N)r!)r0r1r1r2tearDownQszTestProcess.tearDownc CsXtj}|j|jtjt}|jtj|jj|j|jt d|_WdQRXdS)N!) psutilProcess assertEqualpidosgetpidr assertRaisesAttributeError)r0psprocr1r1r2test_pidTs  zTestProcess.test_pidcCsNt}|j}tj|}|j|j}|jtj|trJ|j |t j dS)N) rr9r6r7killwait assertFalse pid_existsrr8signalSIGKILL)r0r?r@r>sigr1r1r2 test_kill\s zTestProcess.test_killcCsNt}|j}tj|}|j|j}|jtj|trJ|j |t j dS)N) rr9r6r7 terminaterBrCrDrr8rESIGTERM)r0r?r@r>rGr1r1r2test_terminatefs zTestProcess.test_terminatec CsLtr tjntj}t}tj|j}|j||j }|j tj |jtrH|j || t}tj|j}|j|t jdttjdd(|jtj|j|WdQRXWdQRXt}tj|j}|j|t jdttjdd,|jtjtjj|WdQRXWdQRXdtjkrHtjd}|jt|jtjdS)Nzpsutil.os.kill) side_effectr)rrErFrJrr6r7r9 send_signalrBrCrDr8rpatchOSErrorerrnoZESRCHr< NoSuchProcessZEPERM AccessDeniedpids ValueError)r0rGr?r>Zexit_sigr1r1r2test_send_signalps2      " zTestProcess.test_send_signalcCs^t}tj|j}|j|j}tr8|j|tj n|j|tj |j |j t}tj|j}|j |j}tr|j|tj n|j|tj |j |j d}ttd|g}tj|j}|j|jd|j |j ttd|g}tj|j}|j|jd|j|jdt}tj|j}|j|jtj|jd|jt|jddS)Nz0import time, sys; time.sleep(0.01); sys.exit(5);z-cg{Gz?)rWN)rr6r7r9rArBrr8rErFrJrC is_runningrIr assertInnamer<TimeoutExpiredrU)r0r?r>coder1r1r2 test_waits<     zTestProcess.test_waitcCst\}}|jtj|jd|jtj|jd|j|j|j}|j}trp|j|tj |j|dn|j|tj |j|tj dS)Ng{Gz?) rr<r6r]rBrIrr8rErJ)r0p1p2Zret1Zret2r1r1r2test_wait_non_childrens z"TestProcess.test_wait_non_childrenc Cst}tj|j}|jtj|jd|jtjd}x:y|jd}Wn$tjk rltj|krhYq:XPq:Wt r|j |t j n|j |t j |j|jdS)Nr)rr6r7r9r<r]rBrAtimerr8rErFrJrCrZ)r0r?r>Zstop_atr^r1r1r2test_wait_timeout_0s    zTestProcess.test_wait_timeout_0c Cstj}|jdd|jddxRtdD]F}|jdd}|j|t|j|dtsd|j|dq*|j|dq*W|j t |jddWdQRXdS)NgMbP?)ZintervaldggY@rXrY) r6r7 cpu_percentrangeassertIsInstancefloatassertGreaterEqualrassertLessEqualr<rU)r0r>xZpercentr1r1r2test_cpu_percents      zTestProcess.test_cpu_percentc Cs*tjddd}tjjWdQRXdS)Nzpsutil.cpu_count)Z return_value)rrOr6r7rg)r0mr1r1r2test_cpu_percent_numcpus_nones z)TestProcess.test_cpu_percent_numcpus_nonecCs8tjj}x&|jD]}tjdtjt||qWdS)Nz%H:%M:%S)r6r7 cpu_times_fieldsrdstrftime localtimegetattr)r0timesr\r1r1r2test_cpu_timess  zTestProcess.test_cpu_timescCstjjdd\}}tjdd\}}t||gt||gdkrZ|jd||ft||gt||gdkr|jd||fdS)Nrcg?zexpected: %s, found: %s)r6r7rqr:rvmaxminfail)r0 user_timeZ kernel_timeutimeZktimer1r1r2test_cpu_times_2s zTestProcess.test_cpu_times_2z not supportedcCsPtj}|j}|j|dtjdkr4|j|d|j|jttjdS)NrrX)r6r7Zcpu_numrk cpu_countr8r[rh)r0r>Znumr1r1r2 test_cpu_nums    zTestProcess.test_cpu_numcCsdt}tj}tj|j}|j}t||}|dkrJ|jd|||ftjdtj |jdS)Nrcz'expected: %s, found: %s, difference: %sz%Y %m %d %H:%M:%S) rrdr6r7r9 create_timeabsrzrsrt)r0r?Znowr>r differencer1r1r2test_create_times  zTestProcess.test_create_timez POSIX onlyznot reliable on TRAVIScCsLtjj}tjjs tjjr>tjj t d}|j ||n |j |dS)Ntty) r6r7terminalsysstdinisattystdoutr:pathrealpathr%r8 assertIsNone)r0rrr1r1r2 test_terminal-s  zTestProcess.test_terminal)Zonly_ifcCstj}|j}ttd}|jWdQRX|j}t rt r|j|j |j |j |j |j t r|j|j |j |j |j|jn |j|j|j|j|j|j|j}tjtd.}tr|jtdddn|jddWdQRX|j}|j|j |j |j|j|j|j|j |j |j|j|jt r^|j|j|j|j|j |j xJtt|D]:}tr|dkrql|j||d|j||dqlWdS)Nrb)prefixrmi@Basciircr)r6r7Z io_countersopenr readrr assertGreaterZ read_countr8Z write_countrZ read_charsZ write_charsrkZ read_bytesZ write_bytestempfileZ TemporaryFiler(r writebytesrhlen)r0r>Zio1fZio2ir1r1r2test_io_counters7s>  zTestProcess.test_io_countersc CstrZioclassvalueoriginalr1r1r2 test_ionicecsJ                      zTestProcess.test_ionicecCst}tj|j}tr|jt|jdd|jt|jdd |jt|jd|jt|jdd|j td|jtj d|j td|jtj d|j td|jdd n"|jt|jd |jt|jdddS) Nrc rXrfooz*can't specify value with IOPRIO_CLASS_NONEz*can't specify value with IOPRIO_CLASS_IDLEz$'ioclass' argument must be specified)rrrY) rr6r7r9rr<rUr TypeErrorZassertRaisesRegexrr)r0r?r>r1r1r2test_ionice_errss$ zTestProcess.test_ionice_errscCsddl}tjtj}ddttD}x|D]}tt|}|j|d|t|kr|j|t||t rlq.|j|j ||j |q.|j |}|jt |d|j|dd|j|ddq.WdS)NrcSsg|]}|jdr|qS)ZRLIMIT) startswith).0rmr1r1r2 sz/TestProcess.test_rlimit_get..rcrXrYrY) resourcer6r7r:r;dirrurkr8rrlimitZ getrlimitr)r0rr>namesr\rretr1r1r2test_rlimit_gets     zTestProcess.test_rlimit_getcCst}tj|j}|jtjd|j|jtjd|jttj jdjdWdQRX|jt|jtjdWdQRXdS)NrWr)rWrW)rWrW)rWrWrW) rr6r7r9r RLIMIT_NOFILEr8r<rUZ _psplatform)r0r?r>r1r1r2test_rlimit_sets   zTestProcess.test_rlimit_setc Cstj}|jtj\}}z|jtjd|fttd}|jddWdQRX|jt*}ttd}|jddWdQRXWdQRX|j t r|j j n|j dt j Wd|jtj||f|j |jtj||fXdS)NiwbXir)r6r7r RLIMIT_FSIZErr)rr<IOErrorr8r Z exceptionrQZEFBIG)r0r>softhardrexcr1r1r2 test_rlimits   " zTestProcess.test_rlimitcCstj}|jtj\}}zN|jtjd|f|jtjtj|fttd}|jddWdQRXWd|jtj||f|j|jtj||fXdS)Nirri) r6r7rr RLIM_INFINITYrr)rr8)r0r>rrrr1r1r2test_rlimit_infinitys z TestProcess.test_rlimit_infinitycCs<tj}|jtj\}}|jtj||jtj||fdS)N)r6r7rrr8r)r0r>rrr1r1r2test_rlimit_infinity_valuesz&TestProcess.test_rlimit_infinity_valuecCsrtj}trstep1step2r1r1r2test_num_threadss zTestProcess.test_num_threadsz WINDOWS onlycCstj}|j|jddS)Nr)r6r7rZ num_handles)r0r>r1r1r2test_num_handles szTestProcess.test_num_handlescCstj}trrrZathreadr1r1r2 test_threadss  zTestProcess.test_threadsc Cst}tj|j}trDy |jWn tjk rBtjdYnX|j |j j t dd|jDdd|j |j j t dd|jDdddS)Nz$on OpenBSD this requires root accesscSsg|] }|jqSr1)r{)rrmr1r1r2r7sz.TestProcess.test_threads_2..g?)ZdeltacSsg|] }|jqSr1)r)rrmr1r1r2r:s)rr6r7r9rrrSr,rZassertAlmostEqualrqusersumsystem)r0r?r>r1r1r2test_threads_2)s   zTestProcess.test_threads_2c Cstj}|jdd\}}|j}|j|d|j|ddgd}|jdd\}}|j}|j|||j|||j||~tr|j} |j| j| j |j| j | j |j} x | j D]} |jt | | dqWdS)Nrcri`)r6r7Z memory_infomemory_percentrrkr r8ZrssZwsetvmsZpagefilerrru) r0r>Zrss1Zvms1Zpercent1ZmemarrZrss2Zvms2Zpercent2memr\r1r1r2test_memory_info<s&       zTestProcess.test_memory_infocCstjj}tjj}xB|jD]8}t||}|j|d||fd|j|||||fdqWt sft sft rt|j|j dt r|j|j d|j|jddS)Nr)msg)r6Zvirtual_memorytotalr7Zmemory_full_inforrrurkrlrr russZpssZswap)r0rrr\rr1r1r2test_memory_full_infoZs     z!TestProcess.test_memory_full_infoc Cstj}|j}dd|D}|jt|tt||jdd}x~|D]v}|jjdsHtryWqt k rt sxn,t d}|j }WdQRXd|j|krYqXqHdt jj|jkrHqHWxN|D]F}x@|jD]6}t||} |d krqq|d krq|j| ttfqWqWdS) NcSsg|]}|qSr1r1)rrmr1r1r2rksz0TestProcess.test_memory_maps..F)Zgrouped[z/proc/self/smapsz %s (deleted)Z64raddrperms)rr)r6r7 memory_mapsr8rsetrrrAssertionErrorrrrr:basenamerrrurirr ) r0r>mapspathsZext_mapsntrdataZfnamerr1r1r2test_memory_mapsgs8         zTestProcess.test_memory_mapsc sHt8}ddfddtjjD}|j||WdQRXdS)NcSstjjtjj|S)N)r:rrnormcase)r>r1r1r2normpathsz8TestProcess.test_memory_maps_lists_lib..normpathcsg|]}|jqSr1)r)rrm)rr1r2rsz:TestProcess.test_memory_maps_lists_lib..)rr6r7rr[)r0rZlibpathsr1)rr2test_memory_maps_lists_libs  z&TestProcess.test_memory_maps_lists_libcCsJtj}|j}|jdd}|jt|jddts:ts:trF|jdd}dS)Nr)Zmemtypez?!?r)r6r7rr<rUrrr )r0r>rr1r1r2test_memory_percents   zTestProcess.test_memory_percentcCs&t}tj|j}|j|jdS)N)rr6r7r9rArB)r0r?r>r1r1r2test_is_runnings  zTestProcess.test_is_runningcCst}tj|jj}y|j|tWntk rtrht |t tkrht j j }|j|||tnNdt jdt jdf}y |j|j|dtj|dWntk rYnXYnXt|ddg}|j|ddS)Nz%s.%srrXrLz-czimport os; print('hey')Zhey)rr6r7r9exer8r rr rr:rrr version_inforeplacer%)r0r?rrZveroutr1r1r2test_exes  zTestProcess.test_exec Cstddg}t|}y(|jdjtj|jjdj|Wn@tk rzt sVt sVt rt|jtj|jjdtnYnXdS)Nz-czimport time; time.sleep(60) r) r rr8joinr6r7r9cmdlinerrrr)r0rr?r1r1r2 test_cmdlines  zTestProcess.test_cmdlinecCs:tt}tj|jjj}tjj tjj t j j}dS)N) rr r6r7r9r\lowerr:rrrr executable)r0r?r\Zpyexer1r1r2 test_nameszTestProcess.test_namezbroken on SUNOSz broken on AIXcsfdd}tdt|j|ddddddg}t|}tj|j}trZt|j|j |j ||j |j t j j|j t j j|jt j jdS) Nc s&y tWntk r YnXdS)N)r$rPr1) funky_pathr1r2rms z.TestProcess.test_prog_w_funky_name..rmz foo bar )z-cz9import time; [time.sleep(0.01) for x in range(3000)];arg1Zarg2rLZarg3)r)r addCleanuprr6r7r9r+r-r8rr\r:rrrr)r0rrr?r>r1)rr2test_prog_w_funky_names     z"TestProcess.test_prog_w_funky_namecCsXtj}|j\}}}|j|tj|j|tjttdrT|jtj|jdS)N getresuid) r6r7uidsr8r:getuidgeteuidhasattrr)r0r>real effectivesavedr1r1r2 test_uidss  zTestProcess.test_uidscCsXtj}|j\}}}|j|tj|j|tjttdrT|jtj|jdS)Nr) r6r7gidsr8r:getgidgetegidr getresgid)r0r>rrrr1r1r2 test_gidss  zTestProcess.test_gidscCstj}|jt|jdtrz||j}tjdkr@|j|t j n |j|t |j |tj |jtj|j |jtj|jtj |j |jtj Wd|jtj Xn|j}zyttdr|j tjtjtj|j|jd|j |jdttdr"|j tjtjtj|jtsB|jd|j |jdWntjk r\YnXWdy|j|Wntjk rYnXXdS)Nstrrr getpriorityrXr)rr)r6r7r<rnicer rrrirrrr8NORMAL_PRIORITY_CLASSZHIGH_PRIORITY_CLASSrr:r PRIO_PROCESSr;rrS)r0r>ZinitZ first_nicer1r1r2 test_nice"sB         zTestProcess.test_nicecCstj}|j|jtjdS)N)r6r7r8statusZSTATUS_RUNNING)r0r>r1r1r2 test_statusKszTestProcess.test_statuscCsnt}tj|j}|j}trZ|jd\}}|j|tj dt j krj|j|t j dn|j|tj dS)N\Z USERDOMAIN) rr6r7r9usernamer splitr8getpassZgetuserr:environ)r0r?r>rZdomainr1r1r2 test_usernameOs  zTestProcess.test_usernamecCs*t}tj|j}|j|jtjdS)N)rr6r7r9r8cwdr:getcwd)r0r?r>r1r1r2test_cwd[s zTestProcess.test_cwdcCs.tddg}t|}tj|j}t|jddS)Nz-cz/import os, time; os.chdir('..'); time.sleep(60)z#ret == os.path.dirname(os.getcwd()))r rr6r7r9rr)r0cmdr?r>r1r1r2 test_cwd_2`s  zTestProcess.test_cwd_2cCstj}|j}|j|j|ttdr@|j|ttj|j |jt |t t |tt t tj dd}xztsz|n|D]j}|j|g|j|j|gttdr|j|jttj|j t|dr~|j|jd|jq~W|jgtr|j|j|jjn|j|j|ttdrL|j|jttj|j |jt|jd|j||jt ||jt|dS)Nsched_getaffinityT)percpunum_cpurrX)r6r7 cpu_affinityrrr:r8listrr9rrrhrgr+rr_procZ_get_eligible_cpusr<rtuple)r0r>initialZall_cpusnr1r1r2test_cpu_affinitygs4         zTestProcess.test_cpu_affinitycCszt}tj|j}ttjdddg}|jt|j||jt|jt dd|jt |jddg|jt|jdd gdS) NT)rri'i*r1rXrY) rr6r7r9rrqr<rUrrhr)r0r?r>Z invalid_cpur1r1r2test_cpu_affinity_errss z"TestProcess.test_cpu_affinity_errscCstj}|j}|j|j|g}xBtdt|dD],}x&tj||D]}|rH|jt |qHWq6Wx&|D]}|j||j |j|qlWdS)NrrX) r6r7rrrhr itertools combinationsappendrr8)r0r>r!ZcomboslZsubsetZcombor1r1r2"test_cpu_affinity_all_combinationss  z.TestProcess.test_cpu_affinity_all_combinationsz broken on BSDzunreliable on APPVEYORc Cs$tj}|j}|jt|kttdn}|jdd|jt|jdt |}x<|D]"}|j tkrZt rz|j |j dPqZW|jdt|WdQRXx |D]}qWdt}ttd|g}tj|j}xBtdD]*}d d |jD}t|krPtjd qW|jt|x|D]}qWdS) Nrxizlen(ret) != %izno file found; files=%sz2import time; f = open(r'%s', 'r'); time.sleep(60);z-crfcSsg|] }|jqSr1)r)rrmr1r1r2rsz/TestProcess.test_open_files..g{Gz?)r6r7 open_filesrCr)rrflushrrrrr8Zpositionrzreprrr r9rhrdsleepr[) r0r>filesrfilerr?rm filenamesr1r1r2test_open_filess4       zTestProcess.test_open_filesc Csttd}tj}xB|jD] }|j|jks<|j|jkrPqW|j dt |j|j |j|jt r||j |jdn|j |j|j|jd}|j |d|j|j |d|j|j |j|jWdQRXdS)Nwzno file found; files=%srXrrY)rr)r6r7r,rr\fdfilenorzr.r8r assertNotIn)r0Zfileobjr>r1Zntupler1r1r2test_open_files_2s  zTestProcess.test_open_files_2cCstj}|j}ttd}|j|j|j|j|dtj}|j|j|j|j|d|j|j|j|j|dS)Nr4rXrc) r6r7Znum_fdsrr)rcloser8socket)r0r>startr1Zsockr1r1r2 test_num_fdss   zTestProcess.test_num_fdsz not reliable on OPENBSD & NETBSDcCsLtj}t|j}x(tdD]}t|j}||krdSqW|jddS)Ni z7num ctx switches still the same after 50.000 iterations)r6r7rZnum_ctx_switchesrhrz)r0r>Zbeforermafterr1r1r2test_num_ctx_switchess  z!TestProcess.test_num_ctx_switchescCsttdr"|jtjjtjtj}t}tj|j }|j|j|t ddt r^dSx2tj D]&}|j |j krzqh|j |j||dqhWdS)NgetppidT) recursive)r)rr:r8r6r7ppidr?r;rr9r!r process_iterassertNotEqual)r0 this_parentr?r>r1r1r2 test_ppids    zTestProcess.test_ppidcCs0tj}t}tj|j}|j|jj|dS)N)r:r;rr6r7r9r8parent)r0rDr?r>r1r1r2 test_parents zTestProcess.test_parentc CsFt}tj|j}tjdtjddd|j|jWdQRXdS)Nzpsutil.Processrr)rM) rr6r7r9rrOrRrrF)r0r?r>r1r1r2test_parent_disappeared s  z#TestProcess.test_parent_disappearedcCstj}|j|jg|j|jddgtdd}|j}|jdd}xL||fD]@}|jt|d|j|dj|j|j|djtj qTWdS)NT)r@r)Z creationflagsrX) r6r7r8childrenrrr9rAr:r;)r0r>r?Z children1Z children2rIr1r1r2 test_children(s  zTestProcess.test_childrencCsdt\}}tj}|j|j|g|j|jdd||g|j|j|j|jddgdS)NT)r@)rr6r7r8rIrIrB)r0r`rar>r1r1r2test_children_recursive7s z#TestProcess.test_children_recursivec Cstjt}x@tjD]4}y||jd7<Wqtjk rFYqXqWt|jddddd}tj |}y|j dd}Wntj k rYnX|j t |t t|dS) NrXcSs|dS)NrXr1)rmr1r1r2Msz6TestProcess.test_children_duplicates..)keyrT)r@rY) collections defaultdictrr6rBrAErrorsorteditemsr7rIrSr8rr)r0tabler>r9cr1r1r2test_children_duplicatesDs   z$TestProcess.test_children_duplicatescCsdt}tj|j}|jx*tdD]}|jtjkr8Ptj dq$W|j |j |jtjdS)Nrfg{Gz?) rr6r7r9suspendrhr ZSTATUS_STOPPEDrdr/resumerC)r0r?r>rmr1r1r2test_suspend_resumeVs zTestProcess.test_suspend_resumecCs$|jttjd|jttjddS)Nr$rXrY)r<rr6r7rU)r0r1r1r2test_invalid_pidaszTestProcess.test_invalid_pidc;Cstj}|jddgd}|jt|jddgtjttj}|jdgdd}t|dt sp|j|ddt j ddtj d "|j|jd gd dd d iWdQRXt j ddtj |jdd |jtj |jd gdWdQRXt j ddtj|jdd "|j|jd gddd diWdQRXt j ddtd F|j}|jd t |j|jt|jd gdWdQRXWdQRX|jt|jdWdQRX|jt|jdgWdQRX|jt|jdd gWdQRXdS) Nrr\)attrsZ connectionsr)rZZad_valuezpsutil.Process.niceT)ZcreaterMr rXZbar)r6r7as_dictr8rQkeysryrT isinstancerrrOrSrRr9r< ZombieProcessNotImplementedErrorr7rrU)r0r>dr1r1r2 test_as_dictes> ""  "   zTestProcess.test_as_dictcCstjd@}tj}|j|j|jWdQRX|j|jdWdQRXtjd}|j|jWdQRX|j|jddS)Nz$psutil._psplatform.Process.cpu_timesrXrc)rrOr6r7oneshotrqr8 call_count)r0ror>r1r1r2 test_oneshots   zTestProcess.test_oneshotc&Cstjd}tjdr}tj}|j:|j|j|j|j|jWdQRXWdQRX|j|jd|j|jdWdQRXWdQRXtjd}|j|jWdQRX|j|jddS)Nz$psutil._psplatform.Process.cpu_timesz(psutil._psplatform.Process.oneshot_enterrXrc)rrOr6r7rbrqr8rc)r0m1m2r>ror1r1r2test_oneshot_twices    " zTestProcess.test_oneshot_twicec Cst}tj|j}|j|jtr8ttjd|j|j |j ddddddg}t rjt rj|j dxTt|D]F}|jd sv||krqvyt||}|d krtr|d }n |tj}np|d kr|}|d }nX|dkr|tj}|tjd}n8|dkr|}|dg}n|dkr(|tj}n|}Wnztjk rV|jd|Yqvtjk rlYqvtjk rtr|dkrnYqvtk rYqvX|jd||fqvWdS)Nz %s not in retr9rZrBrrbZmemory_info_exr_r rXrrcrWrrrNz/ZombieProcess for %r was not supposed to happenrrz4NoSuchProcess exception not raised for %r, retval=%s)rWrW)rr)rr6r7r9rIrBr rrTrCrZrrr(rrrurr rrErJr^rzrRrSrr_)r0r?r>Zexcluded_namesr\methrr1r1r2test_halfway_terminated_processs^               z+TestProcess.test_halfway_terminated_processcCsdd}t}|jtddtj|}|j|jtj|j|j |j ||j }|dk rl|j|gt |dr||j tj||j tjd||jt |dry||jdgWn:tk r}ztrtrd t|krnWYdd}~XnX||jdt |d r0tr$||jd dn ||jdt |drL||j tjd||j ||j||j||j|jtj|t rtr|j|tj|j|d d tjDit_|j|dd tjDdS)Nc _s,y |||Stjtjfk r&YnXdS)N)r6r^rS)Zfunargskwargsr1r1r2succeed_or_zombie_p_excs z@TestProcess.test_zombie_process..succeed_or_zombie_p_excT)r@rrWrrz not eligiblerrccSsg|] }|jqSr1)r9)rrmr1r1r2r9sz3TestProcess.test_zombie_process..cSsg|] }|jqSr1)r9)rrmr1r1r2r;s)rWrW)rWrW) rrr!r6r7r8r  STATUS_ZOMBIE assertTruerZr[rVrrrrFrrUr+rrr rrWrIrArDrr[rTrBZ_pmap)r0rmZzpidZzprocrerrr1r1r2test_zombie_processsP                zTestProcess.test_zombie_processc Cs,tj}tjdtjdd}WdQRXdS)Nzpsutil.Processr)rM)r6r7rrOr^)r0r>ror1r1r2$test_zombie_process_is_running_w_exc=sz0TestProcess.test_zombie_process_is_running_w_excc Cs>tj}tjdtjdd}|j|jtjWdQRXdS)Nz!psutil._psplatform.Process.statusr)rM)r6r7rrOr^r8r rn)r0r>ror1r1r2 test_zombie_process_status_w_excGs z,TestProcess.test_zombie_process_status_w_excc Cs*dtjkr"|jtjtjddStjd}xtjD]}|dkrBq4t||}y |}Wntjk rlYq4X|d kr|j|j dq4|dkrt r|j|j dqt r|j|j dq4|dkr4q4Wt |d ry|jtjWntjk rYnX|jts&|jdtj|jtjddS) Nrr9rrrrootzNT AUTHORITY\SYSTEMr\r)rr)r6rTr<rRr7Z_as_dict_attrnamesrurSr8rrrr rrrr[rr[rorD)r0r>r\rirr1r1r2 test_pid_0Qs<      zTestProcess.test_pid_0cCs@dd}d|_tj}||j}|tjj}|j||dS)NcSsb|jdd|jdd|jddtrL|jdd|jdd|jddtdd|jDS) NZPSUTIL_TESTINGZPLATHOMEZ__CF_USER_TEXT_ENCODINGZVERSIONER_PYTHON_PREFER_32_BITZVERSIONER_PYTHON_VERSIONcSs$g|]\}}|jd|jdfqS)z )rstrip)rkvr1r1r2rsz@TestProcess.test_environ..clean_dict..)poprdictrR)r`r1r1r2 clean_dictzs      z,TestProcess.test_environ..clean_dict)ZmaxDiffr6r7rr:copyr8)r0r|r>Zd1Zd2r1r1r2 test_environxs   zTestProcess.test_environcCstjd}t}t||d|jt|t|gtjtjd}t j |j }t |j |j |j|j|jjd|j|jddd|j|j|jddS) Na #include #include char * const argv[] = {"cat", 0}; char * const envp[] = {"A=1", "X", "C=3", 0}; int main(void) { /* Close stderr on exec so parent can wait for the execve to * finish. */ if (fcntl(2, F_SETFD, FD_CLOEXEC) != 0) return 0; return execve("/bin/cat", argv, envp); } )Zc_code)rstderrr$3)ACr)textwrapdedentr)rrr$r subprocessPIPEr6r7r9r-rorZr8rrr communicate returncode)r0r^rr?r>r1r1r2test_weird_environs      zTestProcess.test_weird_environN)d__name__ __module__ __qualname____doc__r3r4r@rHrKrVr_rbrernrprwr}r,ZskipIfrrrrr+rrr'rrrr rr.rrrrrrrrrrrrr"r&rrrrrrrrrrrrr rrrrr rrrrrr#r%r*rr r3r8r<rrr>rErGrHrJrKrUrXrYrardrgrjrqrrrsrurr~rr1r1r1r2r/Ks   /     +  . "   )    ) *  %    . @I  ' r/c@sReZdZdZeedr&ejZejZ ddZ ddZ ddZ d d Z d d Zd S)LimitedUserTestCasezRepeat the previous tests by using a limited user. Executed only on UNIX and only if the user who run the test script is root. rcs\tj|f||xDddt|DD].}t||fdd}t||tj||q&WdS)NcSsg|]}|jdr|qS)Ztest)r)rrmr1r1r2rsz0LimitedUserTestCase.__init__..c s&y Wntjk r YnXdS)N)r6rS)r0)rir1r2test_s z+LimitedUserTestCase.__init__..test_)r/__init__rrusetattrtypes MethodType)r0rkrlattrrr1)rir2rs   zLimitedUserTestCase.__init__cCs*tttj|tjdtjddS)Ni)r$r)r/r3r:setegidseteuid)r0r1r1r2r3s  zLimitedUserTestCase.setUpcCs&tj|jtj|jtj|dS)N)r:r PROCESS_UIDr PROCESS_GIDr/r4)r0r1r1r2r4s  zLimitedUserTestCase.tearDownc Cs8ytjjdWntjk r(Yn X|jddS)NrXzexception not raisedrY)r6r7r rSrz)r0r1r1r2r s zLimitedUserTestCase.test_nicecCsdS)Nr1)r0r1r1r2rqsz'LimitedUserTestCase.test_zombie_processN)rrrrrr:rrrrrr3r4r rqr1r1r1r2rs rc@s0eZdZdZddZddZddZdd Zd S) TestPopenzTests for psutil.Popen class.cCs tdS)N)r!)r0r1r1r2r4szTestPopen.tearDownc Csjtddg}tj|tjtjdB}|j|j|j|jt ||j t t |d|j WdQRXdS)Nz-czimport time; time.sleep(60);)rrr)r r6Popenrrr\rqrrorr<r=rurI)r0rprocr1r1r2 test_miscs   zTestPopen.test_miscc CsBtjtdgtjtjtjd}|jWdQRX|j|jddS)Nz-V)rrrr)r6rr rrrr8r)r0rr1r1r2test_ctx_managers   zTestPopen.test_ctx_managerc Cstddg}tj|tjtjd}|j|j|jtj|j|jtj|j |jtj|j t j t rtjdkr|jtj|j t j|jtj|j t jWdQRXdS)Nz-czimport time; time.sleep(60);)rrrcr)rcr)r r6rrrrIrBr<rRrArNrErJr rrZ CTRL_C_EVENTZCTRL_BREAK_EVENT)r0rrr1r1r2test_kill_terminates      zTestPopen.test_kill_terminateN)rrrrr4rrrr1r1r1r2rs  r__main__)ErrNrQrr&r:rEr:rrrrrdrr6rrrrrrrr r Zpsutil._compatr r Z psutil.testsr rrrrrrrrrrrrrrrrrrr r!r"r#r$r%r&r'r(r)r*r+r,r-r.ZTestCaser/rrrr__file__r1r1r1r2s                                             q53 PK!//test_system.pynu[ # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Tests for system APIS.""" import contextlib import datetime import errno import os import pprint import shutil import signal import socket import sys import tempfile import time import psutil from psutil import AIX from psutil import BSD from psutil import FREEBSD from psutil import LINUX from psutil import NETBSD from psutil import OPENBSD from psutil import OSX from psutil import POSIX from psutil import SUNOS from psutil import WINDOWS from psutil._compat import long from psutil.tests import APPVEYOR from psutil.tests import ASCII_FS from psutil.tests import check_net_address from psutil.tests import DEVNULL from psutil.tests import enum from psutil.tests import get_test_subprocess from psutil.tests import HAS_BATTERY from psutil.tests import HAS_CPU_FREQ from psutil.tests import HAS_SENSORS_BATTERY from psutil.tests import HAS_SENSORS_FANS from psutil.tests import HAS_SENSORS_TEMPERATURES from psutil.tests import mock from psutil.tests import reap_children from psutil.tests import retry_before_failing from psutil.tests import run_test_module_by_name from psutil.tests import safe_rmpath from psutil.tests import TESTFN from psutil.tests import TESTFN_UNICODE from psutil.tests import TRAVIS from psutil.tests import unittest # =================================================================== # --- System-related API tests # =================================================================== class TestSystemAPIs(unittest.TestCase): """Tests for system-related APIs.""" def setUp(self): safe_rmpath(TESTFN) def tearDown(self): reap_children() def test_process_iter(self): self.assertIn(os.getpid(), [x.pid for x in psutil.process_iter()]) sproc = get_test_subprocess() self.assertIn(sproc.pid, [x.pid for x in psutil.process_iter()]) p = psutil.Process(sproc.pid) p.kill() p.wait() self.assertNotIn(sproc.pid, [x.pid for x in psutil.process_iter()]) with mock.patch('psutil.Process', side_effect=psutil.NoSuchProcess(os.getpid())): self.assertEqual(list(psutil.process_iter()), []) with mock.patch('psutil.Process', side_effect=psutil.AccessDenied(os.getpid())): with self.assertRaises(psutil.AccessDenied): list(psutil.process_iter()) def test_prcess_iter_w_params(self): for p in psutil.process_iter(attrs=['pid']): self.assertEqual(list(p.info.keys()), ['pid']) with self.assertRaises(ValueError): list(psutil.process_iter(attrs=['foo'])) with mock.patch("psutil._psplatform.Process.cpu_times", side_effect=psutil.AccessDenied(0, "")) as m: for p in psutil.process_iter(attrs=["pid", "cpu_times"]): self.assertIsNone(p.info['cpu_times']) self.assertGreaterEqual(p.info['pid'], 0) assert m.called with mock.patch("psutil._psplatform.Process.cpu_times", side_effect=psutil.AccessDenied(0, "")) as m: flag = object() for p in psutil.process_iter( attrs=["pid", "cpu_times"], ad_value=flag): self.assertIs(p.info['cpu_times'], flag) self.assertGreaterEqual(p.info['pid'], 0) assert m.called def test_wait_procs(self): def callback(p): pids.append(p.pid) pids = [] sproc1 = get_test_subprocess() sproc2 = get_test_subprocess() sproc3 = get_test_subprocess() procs = [psutil.Process(x.pid) for x in (sproc1, sproc2, sproc3)] self.assertRaises(ValueError, psutil.wait_procs, procs, timeout=-1) self.assertRaises(TypeError, psutil.wait_procs, procs, callback=1) t = time.time() gone, alive = psutil.wait_procs(procs, timeout=0.01, callback=callback) self.assertLess(time.time() - t, 0.5) self.assertEqual(gone, []) self.assertEqual(len(alive), 3) self.assertEqual(pids, []) for p in alive: self.assertFalse(hasattr(p, 'returncode')) @retry_before_failing(30) def test(procs, callback): gone, alive = psutil.wait_procs(procs, timeout=0.03, callback=callback) self.assertEqual(len(gone), 1) self.assertEqual(len(alive), 2) return gone, alive sproc3.terminate() gone, alive = test(procs, callback) self.assertIn(sproc3.pid, [x.pid for x in gone]) if POSIX: self.assertEqual(gone.pop().returncode, -signal.SIGTERM) else: self.assertEqual(gone.pop().returncode, 1) self.assertEqual(pids, [sproc3.pid]) for p in alive: self.assertFalse(hasattr(p, 'returncode')) @retry_before_failing(30) def test(procs, callback): gone, alive = psutil.wait_procs(procs, timeout=0.03, callback=callback) self.assertEqual(len(gone), 3) self.assertEqual(len(alive), 0) return gone, alive sproc1.terminate() sproc2.terminate() gone, alive = test(procs, callback) self.assertEqual(set(pids), set([sproc1.pid, sproc2.pid, sproc3.pid])) for p in gone: self.assertTrue(hasattr(p, 'returncode')) def test_wait_procs_no_timeout(self): sproc1 = get_test_subprocess() sproc2 = get_test_subprocess() sproc3 = get_test_subprocess() procs = [psutil.Process(x.pid) for x in (sproc1, sproc2, sproc3)] for p in procs: p.terminate() gone, alive = psutil.wait_procs(procs) def test_boot_time(self): bt = psutil.boot_time() self.assertIsInstance(bt, float) self.assertGreater(bt, 0) self.assertLess(bt, time.time()) @unittest.skipIf(not POSIX, 'POSIX only') def test_PAGESIZE(self): # pagesize is used internally to perform different calculations # and it's determined by using SC_PAGE_SIZE; make sure # getpagesize() returns the same value. import resource self.assertEqual(os.sysconf("SC_PAGE_SIZE"), resource.getpagesize()) def test_virtual_memory(self): mem = psutil.virtual_memory() assert mem.total > 0, mem assert mem.available > 0, mem assert 0 <= mem.percent <= 100, mem assert mem.used > 0, mem assert mem.free >= 0, mem for name in mem._fields: value = getattr(mem, name) if name != 'percent': self.assertIsInstance(value, (int, long)) if name != 'total': if not value >= 0: self.fail("%r < 0 (%s)" % (name, value)) if value > mem.total: self.fail("%r > total (total=%s, %s=%s)" % (name, mem.total, name, value)) def test_swap_memory(self): mem = psutil.swap_memory() self.assertEqual( mem._fields, ('total', 'used', 'free', 'percent', 'sin', 'sout')) assert mem.total >= 0, mem assert mem.used >= 0, mem if mem.total > 0: # likely a system with no swap partition assert mem.free > 0, mem else: assert mem.free == 0, mem assert 0 <= mem.percent <= 100, mem assert mem.sin >= 0, mem assert mem.sout >= 0, mem def test_pid_exists(self): sproc = get_test_subprocess() self.assertTrue(psutil.pid_exists(sproc.pid)) p = psutil.Process(sproc.pid) p.kill() p.wait() self.assertFalse(psutil.pid_exists(sproc.pid)) self.assertFalse(psutil.pid_exists(-1)) self.assertEqual(psutil.pid_exists(0), 0 in psutil.pids()) def test_pid_exists_2(self): reap_children() pids = psutil.pids() for pid in pids: try: assert psutil.pid_exists(pid) except AssertionError: # in case the process disappeared in meantime fail only # if it is no longer in psutil.pids() time.sleep(.1) if pid in psutil.pids(): self.fail(pid) pids = range(max(pids) + 5000, max(pids) + 6000) for pid in pids: self.assertFalse(psutil.pid_exists(pid), msg=pid) def test_pids(self): plist = [x.pid for x in psutil.process_iter()] pidlist = psutil.pids() self.assertEqual(plist.sort(), pidlist.sort()) # make sure every pid is unique self.assertEqual(len(pidlist), len(set(pidlist))) def test_test(self): # test for psutil.test() function stdout = sys.stdout sys.stdout = DEVNULL try: psutil.test() finally: sys.stdout = stdout def test_cpu_count(self): logical = psutil.cpu_count() self.assertEqual(logical, len(psutil.cpu_times(percpu=True))) self.assertGreaterEqual(logical, 1) # if os.path.exists("/proc/cpuinfo"): with open("/proc/cpuinfo") as fd: cpuinfo_data = fd.read() if "physical id" not in cpuinfo_data: raise unittest.SkipTest("cpuinfo doesn't include physical id") physical = psutil.cpu_count(logical=False) self.assertGreaterEqual(physical, 1) self.assertGreaterEqual(logical, physical) def test_cpu_count_none(self): # https://github.com/giampaolo/psutil/issues/1085 for val in (-1, 0, None): with mock.patch('psutil._psplatform.cpu_count_logical', return_value=val) as m: self.assertIsNone(psutil.cpu_count()) assert m.called with mock.patch('psutil._psplatform.cpu_count_physical', return_value=val) as m: self.assertIsNone(psutil.cpu_count(logical=False)) assert m.called def test_cpu_times(self): # Check type, value >= 0, str(). total = 0 times = psutil.cpu_times() sum(times) for cp_time in times: self.assertIsInstance(cp_time, float) self.assertGreaterEqual(cp_time, 0.0) total += cp_time self.assertEqual(total, sum(times)) str(times) # CPU times are always supposed to increase over time # or at least remain the same and that's because time # cannot go backwards. # Surprisingly sometimes this might not be the case (at # least on Windows and Linux), see: # https://github.com/giampaolo/psutil/issues/392 # https://github.com/giampaolo/psutil/issues/645 # if not WINDOWS: # last = psutil.cpu_times() # for x in range(100): # new = psutil.cpu_times() # for field in new._fields: # new_t = getattr(new, field) # last_t = getattr(last, field) # self.assertGreaterEqual(new_t, last_t, # msg="%s %s" % (new_t, last_t)) # last = new def test_cpu_times_time_increases(self): # Make sure time increases between calls. t1 = sum(psutil.cpu_times()) time.sleep(0.1) t2 = sum(psutil.cpu_times()) difference = t2 - t1 if not difference >= 0.05: self.fail("difference %s" % difference) def test_per_cpu_times(self): # Check type, value >= 0, str(). for times in psutil.cpu_times(percpu=True): total = 0 sum(times) for cp_time in times: self.assertIsInstance(cp_time, float) self.assertGreaterEqual(cp_time, 0.0) total += cp_time self.assertEqual(total, sum(times)) str(times) self.assertEqual(len(psutil.cpu_times(percpu=True)[0]), len(psutil.cpu_times(percpu=False))) # Note: in theory CPU times are always supposed to increase over # time or remain the same but never go backwards. In practice # sometimes this is not the case. # This issue seemd to be afflict Windows: # https://github.com/giampaolo/psutil/issues/392 # ...but it turns out also Linux (rarely) behaves the same. # last = psutil.cpu_times(percpu=True) # for x in range(100): # new = psutil.cpu_times(percpu=True) # for index in range(len(new)): # newcpu = new[index] # lastcpu = last[index] # for field in newcpu._fields: # new_t = getattr(newcpu, field) # last_t = getattr(lastcpu, field) # self.assertGreaterEqual( # new_t, last_t, msg="%s %s" % (lastcpu, newcpu)) # last = new def test_per_cpu_times_2(self): # Simulate some work load then make sure time have increased # between calls. tot1 = psutil.cpu_times(percpu=True) stop_at = time.time() + 0.1 while True: if time.time() >= stop_at: break tot2 = psutil.cpu_times(percpu=True) for t1, t2 in zip(tot1, tot2): t1, t2 = sum(t1), sum(t2) difference = t2 - t1 if difference >= 0.05: return self.fail() def test_cpu_times_comparison(self): # Make sure the sum of all per cpu times is almost equal to # base "one cpu" times. base = psutil.cpu_times() per_cpu = psutil.cpu_times(percpu=True) summed_values = base._make([sum(num) for num in zip(*per_cpu)]) for field in base._fields: self.assertAlmostEqual( getattr(base, field), getattr(summed_values, field), delta=1) def _test_cpu_percent(self, percent, last_ret, new_ret): try: self.assertIsInstance(percent, float) self.assertGreaterEqual(percent, 0.0) self.assertIsNot(percent, -0.0) self.assertLessEqual(percent, 100.0 * psutil.cpu_count()) except AssertionError as err: raise AssertionError("\n%s\nlast=%s\nnew=%s" % ( err, pprint.pformat(last_ret), pprint.pformat(new_ret))) def test_cpu_percent(self): last = psutil.cpu_percent(interval=0.001) for x in range(100): new = psutil.cpu_percent(interval=None) self._test_cpu_percent(new, last, new) last = new with self.assertRaises(ValueError): psutil.cpu_percent(interval=-1) def test_per_cpu_percent(self): last = psutil.cpu_percent(interval=0.001, percpu=True) self.assertEqual(len(last), psutil.cpu_count()) for x in range(100): new = psutil.cpu_percent(interval=None, percpu=True) for percent in new: self._test_cpu_percent(percent, last, new) last = new with self.assertRaises(ValueError): psutil.cpu_percent(interval=-1, percpu=True) def test_cpu_times_percent(self): last = psutil.cpu_times_percent(interval=0.001) for x in range(100): new = psutil.cpu_times_percent(interval=None) for percent in new: self._test_cpu_percent(percent, last, new) self._test_cpu_percent(sum(new), last, new) last = new def test_per_cpu_times_percent(self): last = psutil.cpu_times_percent(interval=0.001, percpu=True) self.assertEqual(len(last), psutil.cpu_count()) for x in range(100): new = psutil.cpu_times_percent(interval=None, percpu=True) for cpu in new: for percent in cpu: self._test_cpu_percent(percent, last, new) self._test_cpu_percent(sum(cpu), last, new) last = new def test_per_cpu_times_percent_negative(self): # see: https://github.com/giampaolo/psutil/issues/645 psutil.cpu_times_percent(percpu=True) zero_times = [x._make([0 for x in range(len(x._fields))]) for x in psutil.cpu_times(percpu=True)] with mock.patch('psutil.cpu_times', return_value=zero_times): for cpu in psutil.cpu_times_percent(percpu=True): for percent in cpu: self._test_cpu_percent(percent, None, None) def test_disk_usage(self): usage = psutil.disk_usage(os.getcwd()) self.assertEqual(usage._fields, ('total', 'used', 'free', 'percent')) assert usage.total > 0, usage assert usage.used > 0, usage assert usage.free > 0, usage assert usage.total > usage.used, usage assert usage.total > usage.free, usage assert 0 <= usage.percent <= 100, usage.percent if hasattr(shutil, 'disk_usage'): # py >= 3.3, see: http://bugs.python.org/issue12442 shutil_usage = shutil.disk_usage(os.getcwd()) tolerance = 5 * 1024 * 1024 # 5MB self.assertEqual(usage.total, shutil_usage.total) self.assertAlmostEqual(usage.free, shutil_usage.free, delta=tolerance) self.assertAlmostEqual(usage.used, shutil_usage.used, delta=tolerance) # if path does not exist OSError ENOENT is expected across # all platforms fname = tempfile.mktemp() with self.assertRaises(OSError) as exc: psutil.disk_usage(fname) self.assertEqual(exc.exception.errno, errno.ENOENT) def test_disk_usage_unicode(self): # See: https://github.com/giampaolo/psutil/issues/416 if ASCII_FS: with self.assertRaises(UnicodeEncodeError): psutil.disk_usage(TESTFN_UNICODE) def test_disk_usage_bytes(self): psutil.disk_usage(b'.') def test_disk_partitions(self): # all = False ls = psutil.disk_partitions(all=False) # on travis we get: # self.assertEqual(p.cpu_affinity(), [n]) # AssertionError: Lists differ: [0, 1, 2, 3, 4, 5, 6, 7,... != [0] self.assertTrue(ls, msg=ls) for disk in ls: self.assertIsInstance(disk.device, str) self.assertIsInstance(disk.mountpoint, str) self.assertIsInstance(disk.fstype, str) self.assertIsInstance(disk.opts, str) if WINDOWS and 'cdrom' in disk.opts: continue if not POSIX: assert os.path.exists(disk.device), disk else: # we cannot make any assumption about this, see: # http://goo.gl/p9c43 disk.device if SUNOS or TRAVIS: # on solaris apparently mount points can also be files assert os.path.exists(disk.mountpoint), disk else: assert os.path.isdir(disk.mountpoint), disk assert disk.fstype, disk # all = True ls = psutil.disk_partitions(all=True) self.assertTrue(ls, msg=ls) for disk in psutil.disk_partitions(all=True): if not WINDOWS: try: os.stat(disk.mountpoint) except OSError as err: if TRAVIS and OSX and err.errno == errno.EIO: continue # http://mail.python.org/pipermail/python-dev/ # 2012-June/120787.html if err.errno not in (errno.EPERM, errno.EACCES): raise else: if SUNOS or TRAVIS: # on solaris apparently mount points can also be files assert os.path.exists(disk.mountpoint), disk else: assert os.path.isdir(disk.mountpoint), disk self.assertIsInstance(disk.fstype, str) self.assertIsInstance(disk.opts, str) def find_mount_point(path): path = os.path.abspath(path) while not os.path.ismount(path): path = os.path.dirname(path) return path.lower() mount = find_mount_point(__file__) mounts = [x.mountpoint.lower() for x in psutil.disk_partitions(all=True)] self.assertIn(mount, mounts) psutil.disk_usage(mount) def test_net_io_counters(self): def check_ntuple(nt): self.assertEqual(nt[0], nt.bytes_sent) self.assertEqual(nt[1], nt.bytes_recv) self.assertEqual(nt[2], nt.packets_sent) self.assertEqual(nt[3], nt.packets_recv) self.assertEqual(nt[4], nt.errin) self.assertEqual(nt[5], nt.errout) self.assertEqual(nt[6], nt.dropin) self.assertEqual(nt[7], nt.dropout) assert nt.bytes_sent >= 0, nt assert nt.bytes_recv >= 0, nt assert nt.packets_sent >= 0, nt assert nt.packets_recv >= 0, nt assert nt.errin >= 0, nt assert nt.errout >= 0, nt assert nt.dropin >= 0, nt assert nt.dropout >= 0, nt ret = psutil.net_io_counters(pernic=False) check_ntuple(ret) ret = psutil.net_io_counters(pernic=True) self.assertNotEqual(ret, []) for key in ret: self.assertTrue(key) self.assertIsInstance(key, str) check_ntuple(ret[key]) def test_net_io_counters_no_nics(self): # Emulate a case where no NICs are installed, see: # https://github.com/giampaolo/psutil/issues/1062 with mock.patch('psutil._psplatform.net_io_counters', return_value={}) as m: self.assertIsNone(psutil.net_io_counters(pernic=False)) self.assertEqual(psutil.net_io_counters(pernic=True), {}) assert m.called def test_net_if_addrs(self): nics = psutil.net_if_addrs() assert nics, nics nic_stats = psutil.net_if_stats() # Not reliable on all platforms (net_if_addrs() reports more # interfaces). # self.assertEqual(sorted(nics.keys()), # sorted(psutil.net_io_counters(pernic=True).keys())) families = set([socket.AF_INET, socket.AF_INET6, psutil.AF_LINK]) for nic, addrs in nics.items(): self.assertIsInstance(nic, str) self.assertEqual(len(set(addrs)), len(addrs)) for addr in addrs: self.assertIsInstance(addr.family, int) self.assertIsInstance(addr.address, str) self.assertIsInstance(addr.netmask, (str, type(None))) self.assertIsInstance(addr.broadcast, (str, type(None))) self.assertIn(addr.family, families) if sys.version_info >= (3, 4): self.assertIsInstance(addr.family, enum.IntEnum) if nic_stats[nic].isup: # Do not test binding to addresses of interfaces # that are down if addr.family == socket.AF_INET: s = socket.socket(addr.family) with contextlib.closing(s): s.bind((addr.address, 0)) elif addr.family == socket.AF_INET6: info = socket.getaddrinfo( addr.address, 0, socket.AF_INET6, socket.SOCK_STREAM, 0, socket.AI_PASSIVE)[0] af, socktype, proto, canonname, sa = info s = socket.socket(af, socktype, proto) with contextlib.closing(s): s.bind(sa) for ip in (addr.address, addr.netmask, addr.broadcast, addr.ptp): if ip is not None: # TODO: skip AF_INET6 for now because I get: # AddressValueError: Only hex digits permitted in # u'c6f3%lxcbr0' in u'fe80::c8e0:fff:fe54:c6f3%lxcbr0' if addr.family != socket.AF_INET6: check_net_address(ip, addr.family) # broadcast and ptp addresses are mutually exclusive if addr.broadcast: self.assertIsNone(addr.ptp) elif addr.ptp: self.assertIsNone(addr.broadcast) if BSD or OSX or SUNOS: if hasattr(socket, "AF_LINK"): self.assertEqual(psutil.AF_LINK, socket.AF_LINK) elif LINUX: self.assertEqual(psutil.AF_LINK, socket.AF_PACKET) elif WINDOWS: self.assertEqual(psutil.AF_LINK, -1) def test_net_if_addrs_mac_null_bytes(self): # Simulate that the underlying C function returns an incomplete # MAC address. psutil is supposed to fill it with null bytes. # https://github.com/giampaolo/psutil/issues/786 if POSIX: ret = [('em1', psutil.AF_LINK, '06:3d:29', None, None, None)] else: ret = [('em1', -1, '06-3d-29', None, None, None)] with mock.patch('psutil._psplatform.net_if_addrs', return_value=ret) as m: addr = psutil.net_if_addrs()['em1'][0] assert m.called if POSIX: self.assertEqual(addr.address, '06:3d:29:00:00:00') else: self.assertEqual(addr.address, '06-3d-29-00-00-00') @unittest.skipIf(TRAVIS, "unreliable on TRAVIS") # raises EPERM def test_net_if_stats(self): nics = psutil.net_if_stats() assert nics, nics all_duplexes = (psutil.NIC_DUPLEX_FULL, psutil.NIC_DUPLEX_HALF, psutil.NIC_DUPLEX_UNKNOWN) for name, stats in nics.items(): self.assertIsInstance(name, str) isup, duplex, speed, mtu = stats self.assertIsInstance(isup, bool) self.assertIn(duplex, all_duplexes) self.assertIn(duplex, all_duplexes) self.assertGreaterEqual(speed, 0) self.assertGreaterEqual(mtu, 0) @unittest.skipIf(LINUX and not os.path.exists('/proc/diskstats'), '/proc/diskstats not available on this linux version') @unittest.skipIf(APPVEYOR and psutil.disk_io_counters() is None, "unreliable on APPVEYOR") # no visible disks def test_disk_io_counters(self): def check_ntuple(nt): self.assertEqual(nt[0], nt.read_count) self.assertEqual(nt[1], nt.write_count) self.assertEqual(nt[2], nt.read_bytes) self.assertEqual(nt[3], nt.write_bytes) if not (OPENBSD or NETBSD): self.assertEqual(nt[4], nt.read_time) self.assertEqual(nt[5], nt.write_time) if LINUX: self.assertEqual(nt[6], nt.read_merged_count) self.assertEqual(nt[7], nt.write_merged_count) self.assertEqual(nt[8], nt.busy_time) elif FREEBSD: self.assertEqual(nt[6], nt.busy_time) for name in nt._fields: assert getattr(nt, name) >= 0, nt ret = psutil.disk_io_counters(perdisk=False) assert ret is not None, "no disks on this system?" check_ntuple(ret) ret = psutil.disk_io_counters(perdisk=True) # make sure there are no duplicates self.assertEqual(len(ret), len(set(ret))) for key in ret: assert key, key check_ntuple(ret[key]) if LINUX and key[-1].isdigit(): # if 'sda1' is listed 'sda' shouldn't, see: # https://github.com/giampaolo/psutil/issues/338 while key[-1].isdigit(): key = key[:-1] self.assertNotIn(key, ret.keys()) def test_disk_io_counters_no_disks(self): # Emulate a case where no disks are installed, see: # https://github.com/giampaolo/psutil/issues/1062 with mock.patch('psutil._psplatform.disk_io_counters', return_value={}) as m: self.assertIsNone(psutil.disk_io_counters(perdisk=False)) self.assertEqual(psutil.disk_io_counters(perdisk=True), {}) assert m.called # can't find users on APPVEYOR or TRAVIS @unittest.skipIf(APPVEYOR or TRAVIS and not psutil.users(), "unreliable on APPVEYOR or TRAVIS") def test_users(self): users = psutil.users() self.assertNotEqual(users, []) for user in users: assert user.name, user self.assertIsInstance(user.name, str) self.assertIsInstance(user.terminal, (str, type(None))) if user.host is not None: self.assertIsInstance(user.host, (str, type(None))) user.terminal user.host assert user.started > 0.0, user datetime.datetime.fromtimestamp(user.started) if WINDOWS or OPENBSD: self.assertIsNone(user.pid) else: psutil.Process(user.pid) def test_cpu_stats(self): # Tested more extensively in per-platform test modules. infos = psutil.cpu_stats() self.assertEqual( infos._fields, ('ctx_switches', 'interrupts', 'soft_interrupts', 'syscalls')) for name in infos._fields: value = getattr(infos, name) self.assertGreaterEqual(value, 0) # on AIX, ctx_switches is always 0 if not AIX and name in ('ctx_switches', 'interrupts'): self.assertGreater(value, 0) @unittest.skipIf(not HAS_CPU_FREQ, "not suported") def test_cpu_freq(self): def check_ls(ls): for nt in ls: self.assertEqual(nt._fields, ('current', 'min', 'max')) self.assertLessEqual(nt.current, nt.max) for name in nt._fields: value = getattr(nt, name) self.assertIsInstance(value, (int, long, float)) self.assertGreaterEqual(value, 0) ls = psutil.cpu_freq(percpu=True) if TRAVIS and not ls: return assert ls, ls check_ls([psutil.cpu_freq(percpu=False)]) if LINUX: self.assertEqual(len(ls), psutil.cpu_count()) def test_os_constants(self): names = ["POSIX", "WINDOWS", "LINUX", "OSX", "FREEBSD", "OPENBSD", "NETBSD", "BSD", "SUNOS"] for name in names: self.assertIsInstance(getattr(psutil, name), bool, msg=name) if os.name == 'posix': assert psutil.POSIX assert not psutil.WINDOWS names.remove("POSIX") if "linux" in sys.platform.lower(): assert psutil.LINUX names.remove("LINUX") elif "bsd" in sys.platform.lower(): assert psutil.BSD self.assertEqual([psutil.FREEBSD, psutil.OPENBSD, psutil.NETBSD].count(True), 1) names.remove("BSD") names.remove("FREEBSD") names.remove("OPENBSD") names.remove("NETBSD") elif "sunos" in sys.platform.lower() or \ "solaris" in sys.platform.lower(): assert psutil.SUNOS names.remove("SUNOS") elif "darwin" in sys.platform.lower(): assert psutil.OSX names.remove("OSX") else: assert psutil.WINDOWS assert not psutil.POSIX names.remove("WINDOWS") # assert all other constants are set to False for name in names: self.assertIs(getattr(psutil, name), False, msg=name) @unittest.skipIf(not HAS_SENSORS_TEMPERATURES, "not supported") def test_sensors_temperatures(self): temps = psutil.sensors_temperatures() for name, entries in temps.items(): self.assertIsInstance(name, str) for entry in entries: self.assertIsInstance(entry.label, str) if entry.current is not None: self.assertGreaterEqual(entry.current, 0) if entry.high is not None: self.assertGreaterEqual(entry.high, 0) if entry.critical is not None: self.assertGreaterEqual(entry.critical, 0) @unittest.skipIf(not HAS_SENSORS_TEMPERATURES, "not supported") def test_sensors_temperatures_fahreneit(self): d = {'coretemp': [('label', 50.0, 60.0, 70.0)]} with mock.patch("psutil._psplatform.sensors_temperatures", return_value=d) as m: temps = psutil.sensors_temperatures( fahrenheit=True)['coretemp'][0] assert m.called self.assertEqual(temps.current, 122.0) self.assertEqual(temps.high, 140.0) self.assertEqual(temps.critical, 158.0) @unittest.skipIf(not HAS_SENSORS_BATTERY, "not supported") @unittest.skipIf(not HAS_BATTERY, "no battery") def test_sensors_battery(self): ret = psutil.sensors_battery() self.assertGreaterEqual(ret.percent, 0) self.assertLessEqual(ret.percent, 100) if ret.secsleft not in (psutil.POWER_TIME_UNKNOWN, psutil.POWER_TIME_UNLIMITED): self.assertGreaterEqual(ret.secsleft, 0) else: if ret.secsleft == psutil.POWER_TIME_UNLIMITED: self.assertTrue(ret.power_plugged) self.assertIsInstance(ret.power_plugged, bool) @unittest.skipIf(not HAS_SENSORS_FANS, "not supported") def test_sensors_fans(self): fans = psutil.sensors_fans() for name, entries in fans.items(): self.assertIsInstance(name, str) for entry in entries: self.assertIsInstance(entry.label, str) self.assertIsInstance(entry.current, (int, long)) self.assertGreaterEqual(entry.current, 0) if __name__ == '__main__': run_test_module_by_name(__file__) PK!Oy?? test_posix.pynu[# -*- coding: utf-8 -*- # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """POSIX specific tests.""" import datetime import errno import os import re import subprocess import sys import time import psutil from psutil import AIX from psutil import BSD from psutil import LINUX from psutil import OPENBSD from psutil import OSX from psutil import POSIX from psutil import SUNOS from psutil._compat import callable from psutil._compat import PY3 from psutil.tests import APPVEYOR from psutil.tests import get_kernel_version from psutil.tests import get_test_subprocess from psutil.tests import mock from psutil.tests import PYTHON_EXE from psutil.tests import reap_children from psutil.tests import retry_before_failing from psutil.tests import run_test_module_by_name from psutil.tests import sh from psutil.tests import skip_on_access_denied from psutil.tests import TRAVIS from psutil.tests import unittest from psutil.tests import wait_for_pid from psutil.tests import which def ps(cmd): """Expects a ps command with a -o argument and parse the result returning only the value of interest. """ if not LINUX: cmd = cmd.replace(" --no-headers ", " ") if SUNOS: cmd = cmd.replace("-o start", "-o stime") if AIX: cmd = cmd.replace("-o rss", "-o rssize") output = sh(cmd) if not LINUX: output = output.split('\n')[1].strip() try: return int(output) except ValueError: return output # ps "-o" field names differ wildly between platforms. # "comm" means "only executable name" but is not available on BSD platforms. # "args" means "command with all its arguments", and is also not available # on BSD platforms. # "command" is like "args" on most platforms, but like "comm" on AIX, # and not available on SUNOS. # so for the executable name we can use "comm" on Solaris and split "command" # on other platforms. # to get the cmdline (with args) we have to use "args" on AIX and # Solaris, and can use "command" on all others. def ps_name(pid): field = "command" if SUNOS: field = "comm" return ps("ps --no-headers -o %s -p %s" % (field, pid)).split(' ')[0] def ps_args(pid): field = "command" if AIX or SUNOS: field = "args" return ps("ps --no-headers -o %s -p %s" % (field, pid)) @unittest.skipIf(not POSIX, "POSIX only") class TestProcess(unittest.TestCase): """Compare psutil results against 'ps' command line utility (mainly).""" @classmethod def setUpClass(cls): cls.pid = get_test_subprocess([PYTHON_EXE, "-E", "-O"], stdin=subprocess.PIPE).pid wait_for_pid(cls.pid) @classmethod def tearDownClass(cls): reap_children() def test_ppid(self): ppid_ps = ps("ps --no-headers -o ppid -p %s" % self.pid) ppid_psutil = psutil.Process(self.pid).ppid() self.assertEqual(ppid_ps, ppid_psutil) def test_uid(self): uid_ps = ps("ps --no-headers -o uid -p %s" % self.pid) uid_psutil = psutil.Process(self.pid).uids().real self.assertEqual(uid_ps, uid_psutil) def test_gid(self): gid_ps = ps("ps --no-headers -o rgid -p %s" % self.pid) gid_psutil = psutil.Process(self.pid).gids().real self.assertEqual(gid_ps, gid_psutil) def test_username(self): username_ps = ps("ps --no-headers -o user -p %s" % self.pid) username_psutil = psutil.Process(self.pid).username() self.assertEqual(username_ps, username_psutil) def test_username_no_resolution(self): # Emulate a case where the system can't resolve the uid to # a username in which case psutil is supposed to return # the stringified uid. p = psutil.Process() with mock.patch("psutil.pwd.getpwuid", side_effect=KeyError) as fun: self.assertEqual(p.username(), str(p.uids().real)) assert fun.called @skip_on_access_denied() @retry_before_failing() def test_rss_memory(self): # give python interpreter some time to properly initialize # so that the results are the same time.sleep(0.1) rss_ps = ps("ps --no-headers -o rss -p %s" % self.pid) rss_psutil = psutil.Process(self.pid).memory_info()[0] / 1024 self.assertEqual(rss_ps, rss_psutil) @skip_on_access_denied() @retry_before_failing() def test_vsz_memory(self): # give python interpreter some time to properly initialize # so that the results are the same time.sleep(0.1) vsz_ps = ps("ps --no-headers -o vsz -p %s" % self.pid) vsz_psutil = psutil.Process(self.pid).memory_info()[1] / 1024 self.assertEqual(vsz_ps, vsz_psutil) def test_name(self): name_ps = ps_name(self.pid) # remove path if there is any, from the command name_ps = os.path.basename(name_ps).lower() name_psutil = psutil.Process(self.pid).name().lower() # ...because of how we calculate PYTHON_EXE; on OSX this may # be "pythonX.Y". name_ps = re.sub(r"\d.\d", "", name_ps) name_psutil = re.sub(r"\d.\d", "", name_psutil) self.assertEqual(name_ps, name_psutil) def test_name_long(self): # On UNIX the kernel truncates the name to the first 15 # characters. In such a case psutil tries to determine the # full name from the cmdline. name = "long-program-name" cmdline = ["long-program-name-extended", "foo", "bar"] with mock.patch("psutil._psplatform.Process.name", return_value=name): with mock.patch("psutil._psplatform.Process.cmdline", return_value=cmdline): p = psutil.Process() self.assertEqual(p.name(), "long-program-name-extended") def test_name_long_cmdline_ad_exc(self): # Same as above but emulates a case where cmdline() raises # AccessDenied in which case psutil is supposed to return # the truncated name instead of crashing. name = "long-program-name" with mock.patch("psutil._psplatform.Process.name", return_value=name): with mock.patch("psutil._psplatform.Process.cmdline", side_effect=psutil.AccessDenied(0, "")): p = psutil.Process() self.assertEqual(p.name(), "long-program-name") def test_name_long_cmdline_nsp_exc(self): # Same as above but emulates a case where cmdline() raises NSP # which is supposed to propagate. name = "long-program-name" with mock.patch("psutil._psplatform.Process.name", return_value=name): with mock.patch("psutil._psplatform.Process.cmdline", side_effect=psutil.NoSuchProcess(0, "")): p = psutil.Process() self.assertRaises(psutil.NoSuchProcess, p.name) @unittest.skipIf(OSX or BSD, 'ps -o start not available') def test_create_time(self): time_ps = ps("ps --no-headers -o start -p %s" % self.pid).split(' ')[0] time_psutil = psutil.Process(self.pid).create_time() time_psutil_tstamp = datetime.datetime.fromtimestamp( time_psutil).strftime("%H:%M:%S") # sometimes ps shows the time rounded up instead of down, so we check # for both possible values round_time_psutil = round(time_psutil) round_time_psutil_tstamp = datetime.datetime.fromtimestamp( round_time_psutil).strftime("%H:%M:%S") self.assertIn(time_ps, [time_psutil_tstamp, round_time_psutil_tstamp]) def test_exe(self): ps_pathname = ps_name(self.pid) psutil_pathname = psutil.Process(self.pid).exe() try: self.assertEqual(ps_pathname, psutil_pathname) except AssertionError: # certain platforms such as BSD are more accurate returning: # "/usr/local/bin/python2.7" # ...instead of: # "/usr/local/bin/python" # We do not want to consider this difference in accuracy # an error. adjusted_ps_pathname = ps_pathname[:len(ps_pathname)] self.assertEqual(ps_pathname, adjusted_ps_pathname) def test_cmdline(self): ps_cmdline = ps_args(self.pid) psutil_cmdline = " ".join(psutil.Process(self.pid).cmdline()) self.assertEqual(ps_cmdline, psutil_cmdline) # On SUNOS "ps" reads niceness /proc/pid/psinfo which returns an # incorrect value (20); the real deal is getpriority(2) which # returns 0; psutil relies on it, see: # https://github.com/giampaolo/psutil/issues/1082 # AIX has the same issue @unittest.skipIf(SUNOS, "not reliable on SUNOS") @unittest.skipIf(AIX, "not reliable on AIX") def test_nice(self): ps_nice = ps("ps --no-headers -o nice -p %s" % self.pid) psutil_nice = psutil.Process().nice() self.assertEqual(ps_nice, psutil_nice) def test_num_fds(self): # Note: this fails from time to time; I'm keen on thinking # it doesn't mean something is broken def call(p, attr): args = () attr = getattr(p, name, None) if attr is not None and callable(attr): if name == 'rlimit': args = (psutil.RLIMIT_NOFILE,) attr(*args) else: attr p = psutil.Process(os.getpid()) failures = [] ignored_names = ['terminate', 'kill', 'suspend', 'resume', 'nice', 'send_signal', 'wait', 'children', 'as_dict', 'memory_info_ex'] if LINUX and get_kernel_version() < (2, 6, 36): ignored_names.append('rlimit') if LINUX and get_kernel_version() < (2, 6, 23): ignored_names.append('num_ctx_switches') for name in dir(psutil.Process): if (name.startswith('_') or name in ignored_names): continue else: try: num1 = p.num_fds() for x in range(2): call(p, name) num2 = p.num_fds() except psutil.AccessDenied: pass else: if abs(num2 - num1) > 1: fail = "failure while processing Process.%s method " \ "(before=%s, after=%s)" % (name, num1, num2) failures.append(fail) if failures: self.fail('\n' + '\n'.join(failures)) @unittest.skipIf(not POSIX, "POSIX only") class TestSystemAPIs(unittest.TestCase): """Test some system APIs.""" @retry_before_failing() def test_pids(self): # Note: this test might fail if the OS is starting/killing # other processes in the meantime if SUNOS or AIX: cmd = ["ps", "-A", "-o", "pid"] else: cmd = ["ps", "ax", "-o", "pid"] p = get_test_subprocess(cmd, stdout=subprocess.PIPE) output = p.communicate()[0].strip() assert p.poll() == 0 if PY3: output = str(output, sys.stdout.encoding) pids_ps = [] for line in output.split('\n')[1:]: if line: pid = int(line.split()[0].strip()) pids_ps.append(pid) # remove ps subprocess pid which is supposed to be dead in meantime pids_ps.remove(p.pid) pids_psutil = psutil.pids() pids_ps.sort() pids_psutil.sort() # on OSX and OPENBSD ps doesn't show pid 0 if OSX or OPENBSD and 0 not in pids_ps: pids_ps.insert(0, 0) self.assertEqual(pids_ps, pids_psutil) # for some reason ifconfig -a does not report all interfaces # returned by psutil @unittest.skipIf(SUNOS, "unreliable on SUNOS") @unittest.skipIf(TRAVIS, "unreliable on TRAVIS") @unittest.skipIf(not which('ifconfig'), "no ifconfig cmd") def test_nic_names(self): output = sh("ifconfig -a") for nic in psutil.net_io_counters(pernic=True).keys(): for line in output.split(): if line.startswith(nic): break else: self.fail( "couldn't find %s nic in 'ifconfig -a' output\n%s" % ( nic, output)) # can't find users on APPVEYOR or TRAVIS @unittest.skipIf(APPVEYOR or TRAVIS and not psutil.users(), "unreliable on APPVEYOR or TRAVIS") @retry_before_failing() def test_users(self): out = sh("who") lines = out.split('\n') users = [x.split()[0] for x in lines] terminals = [x.split()[1] for x in lines] self.assertEqual(len(users), len(psutil.users())) for u in psutil.users(): self.assertIn(u.name, users) self.assertIn(u.terminal, terminals) def test_pid_exists_let_raise(self): # According to "man 2 kill" possible error values for kill # are (EINVAL, EPERM, ESRCH). Test that any other errno # results in an exception. with mock.patch("psutil._psposix.os.kill", side_effect=OSError(errno.EBADF, "")) as m: self.assertRaises(OSError, psutil._psposix.pid_exists, os.getpid()) assert m.called def test_os_waitpid_let_raise(self): # os.waitpid() is supposed to catch EINTR and ECHILD only. # Test that any other errno results in an exception. with mock.patch("psutil._psposix.os.waitpid", side_effect=OSError(errno.EBADF, "")) as m: self.assertRaises(OSError, psutil._psposix.wait_pid, os.getpid()) assert m.called def test_os_waitpid_eintr(self): # os.waitpid() is supposed to "retry" on EINTR. with mock.patch("psutil._psposix.os.waitpid", side_effect=OSError(errno.EINTR, "")) as m: self.assertRaises( psutil._psposix.TimeoutExpired, psutil._psposix.wait_pid, os.getpid(), timeout=0.01) assert m.called def test_os_waitpid_bad_ret_status(self): # Simulate os.waitpid() returning a bad status. with mock.patch("psutil._psposix.os.waitpid", return_value=(1, -1)) as m: self.assertRaises(ValueError, psutil._psposix.wait_pid, os.getpid()) assert m.called # AIX can return '-' in df output instead of numbers, e.g. for /proc @unittest.skipIf(AIX, "unreliable on AIX") def test_disk_usage(self): def df(device): out = sh("df -k %s" % device).strip() line = out.split('\n')[1] fields = line.split() total = int(fields[1]) * 1024 used = int(fields[2]) * 1024 free = int(fields[3]) * 1024 percent = float(fields[4].replace('%', '')) return (total, used, free, percent) tolerance = 4 * 1024 * 1024 # 4MB for part in psutil.disk_partitions(all=False): usage = psutil.disk_usage(part.mountpoint) try: total, used, free, percent = df(part.device) except RuntimeError as err: # see: # https://travis-ci.org/giampaolo/psutil/jobs/138338464 # https://travis-ci.org/giampaolo/psutil/jobs/138343361 err = str(err).lower() if "no such file or directory" in err or \ "raw devices not supported" in err or \ "permission denied" in err: continue else: raise else: self.assertAlmostEqual(usage.total, total, delta=tolerance) self.assertAlmostEqual(usage.used, used, delta=tolerance) self.assertAlmostEqual(usage.free, free, delta=tolerance) self.assertAlmostEqual(usage.percent, percent, delta=1) if __name__ == '__main__': run_test_module_by_name(__file__) PK!9loPcEcE test_bsd.pynu[ # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # TODO: (FreeBSD) add test for comparing connections with 'sockstat' cmd. """Tests specific to all BSD platforms.""" import datetime import os import re import time import psutil from psutil import BSD from psutil import FREEBSD from psutil import NETBSD from psutil import OPENBSD from psutil.tests import get_test_subprocess from psutil.tests import HAS_BATTERY from psutil.tests import MEMORY_TOLERANCE from psutil.tests import reap_children from psutil.tests import retry_before_failing from psutil.tests import run_test_module_by_name from psutil.tests import sh from psutil.tests import unittest from psutil.tests import which if BSD: PAGESIZE = os.sysconf("SC_PAGE_SIZE") if os.getuid() == 0: # muse requires root privileges MUSE_AVAILABLE = which('muse') else: MUSE_AVAILABLE = False else: MUSE_AVAILABLE = False def sysctl(cmdline): """Expects a sysctl command with an argument and parse the result returning only the value of interest. """ result = sh("sysctl " + cmdline) if FREEBSD: result = result[result.find(": ") + 2:] elif OPENBSD or NETBSD: result = result[result.find("=") + 1:] try: return int(result) except ValueError: return result def muse(field): """Thin wrapper around 'muse' cmdline utility.""" out = sh('muse') for line in out.split('\n'): if line.startswith(field): break else: raise ValueError("line not found") return int(line.split()[1]) # ===================================================================== # --- All BSD* # ===================================================================== @unittest.skipIf(not BSD, "BSD only") class BSDSpecificTestCase(unittest.TestCase): """Generic tests common to all BSD variants.""" @classmethod def setUpClass(cls): cls.pid = get_test_subprocess().pid @classmethod def tearDownClass(cls): reap_children() @unittest.skipIf(NETBSD, "-o lstart doesn't work on NETBSD") def test_process_create_time(self): output = sh("ps -o lstart -p %s" % self.pid) start_ps = output.replace('STARTED', '').strip() start_psutil = psutil.Process(self.pid).create_time() start_psutil = time.strftime("%a %b %e %H:%M:%S %Y", time.localtime(start_psutil)) self.assertEqual(start_ps, start_psutil) def test_disks(self): # test psutil.disk_usage() and psutil.disk_partitions() # against "df -a" def df(path): out = sh('df -k "%s"' % path).strip() lines = out.split('\n') lines.pop(0) line = lines.pop(0) dev, total, used, free = line.split()[:4] if dev == 'none': dev = '' total = int(total) * 1024 used = int(used) * 1024 free = int(free) * 1024 return dev, total, used, free for part in psutil.disk_partitions(all=False): usage = psutil.disk_usage(part.mountpoint) dev, total, used, free = df(part.mountpoint) self.assertEqual(part.device, dev) self.assertEqual(usage.total, total) # 10 MB tollerance if abs(usage.free - free) > 10 * 1024 * 1024: self.fail("psutil=%s, df=%s" % (usage.free, free)) if abs(usage.used - used) > 10 * 1024 * 1024: self.fail("psutil=%s, df=%s" % (usage.used, used)) @unittest.skipIf(not which('sysctl'), "sysctl cmd not available") def test_cpu_count_logical(self): syst = sysctl("hw.ncpu") self.assertEqual(psutil.cpu_count(logical=True), syst) @unittest.skipIf(not which('sysctl'), "sysctl cmd not available") def test_virtual_memory_total(self): num = sysctl('hw.physmem') self.assertEqual(num, psutil.virtual_memory().total) def test_net_if_stats(self): for name, stats in psutil.net_if_stats().items(): try: out = sh("ifconfig %s" % name) except RuntimeError: pass else: self.assertEqual(stats.isup, 'RUNNING' in out, msg=out) if "mtu" in out: self.assertEqual(stats.mtu, int(re.findall(r'mtu (\d+)', out)[0])) # ===================================================================== # --- FreeBSD # ===================================================================== @unittest.skipIf(not FREEBSD, "FREEBSD only") class FreeBSDSpecificTestCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.pid = get_test_subprocess().pid @classmethod def tearDownClass(cls): reap_children() @retry_before_failing() def test_proc_memory_maps(self): out = sh('procstat -v %s' % self.pid) maps = psutil.Process(self.pid).memory_maps(grouped=False) lines = out.split('\n')[1:] while lines: line = lines.pop() fields = line.split() _, start, stop, perms, res = fields[:5] map = maps.pop() self.assertEqual("%s-%s" % (start, stop), map.addr) self.assertEqual(int(res), map.rss) if not map.path.startswith('['): self.assertEqual(fields[10], map.path) def test_proc_exe(self): out = sh('procstat -b %s' % self.pid) self.assertEqual(psutil.Process(self.pid).exe(), out.split('\n')[1].split()[-1]) def test_proc_cmdline(self): out = sh('procstat -c %s' % self.pid) self.assertEqual(' '.join(psutil.Process(self.pid).cmdline()), ' '.join(out.split('\n')[1].split()[2:])) def test_proc_uids_gids(self): out = sh('procstat -s %s' % self.pid) euid, ruid, suid, egid, rgid, sgid = out.split('\n')[1].split()[2:8] p = psutil.Process(self.pid) uids = p.uids() gids = p.gids() self.assertEqual(uids.real, int(ruid)) self.assertEqual(uids.effective, int(euid)) self.assertEqual(uids.saved, int(suid)) self.assertEqual(gids.real, int(rgid)) self.assertEqual(gids.effective, int(egid)) self.assertEqual(gids.saved, int(sgid)) @retry_before_failing() def test_proc_ctx_switches(self): tested = [] out = sh('procstat -r %s' % self.pid) p = psutil.Process(self.pid) for line in out.split('\n'): line = line.lower().strip() if ' voluntary context' in line: pstat_value = int(line.split()[-1]) psutil_value = p.num_ctx_switches().voluntary self.assertEqual(pstat_value, psutil_value) tested.append(None) elif ' involuntary context' in line: pstat_value = int(line.split()[-1]) psutil_value = p.num_ctx_switches().involuntary self.assertEqual(pstat_value, psutil_value) tested.append(None) if len(tested) != 2: raise RuntimeError("couldn't find lines match in procstat out") @retry_before_failing() def test_proc_cpu_times(self): tested = [] out = sh('procstat -r %s' % self.pid) p = psutil.Process(self.pid) for line in out.split('\n'): line = line.lower().strip() if 'user time' in line: pstat_value = float('0.' + line.split()[-1].split('.')[-1]) psutil_value = p.cpu_times().user self.assertEqual(pstat_value, psutil_value) tested.append(None) elif 'system time' in line: pstat_value = float('0.' + line.split()[-1].split('.')[-1]) psutil_value = p.cpu_times().system self.assertEqual(pstat_value, psutil_value) tested.append(None) if len(tested) != 2: raise RuntimeError("couldn't find lines match in procstat out") # --- virtual_memory(); tests against sysctl @retry_before_failing() def test_vmem_active(self): syst = sysctl("vm.stats.vm.v_active_count") * PAGESIZE self.assertAlmostEqual(psutil.virtual_memory().active, syst, delta=MEMORY_TOLERANCE) @retry_before_failing() def test_vmem_inactive(self): syst = sysctl("vm.stats.vm.v_inactive_count") * PAGESIZE self.assertAlmostEqual(psutil.virtual_memory().inactive, syst, delta=MEMORY_TOLERANCE) @retry_before_failing() def test_vmem_wired(self): syst = sysctl("vm.stats.vm.v_wire_count") * PAGESIZE self.assertAlmostEqual(psutil.virtual_memory().wired, syst, delta=MEMORY_TOLERANCE) @retry_before_failing() def test_vmem_cached(self): syst = sysctl("vm.stats.vm.v_cache_count") * PAGESIZE self.assertAlmostEqual(psutil.virtual_memory().cached, syst, delta=MEMORY_TOLERANCE) @retry_before_failing() def test_vmem_free(self): syst = sysctl("vm.stats.vm.v_free_count") * PAGESIZE self.assertAlmostEqual(psutil.virtual_memory().free, syst, delta=MEMORY_TOLERANCE) @retry_before_failing() def test_vmem_buffers(self): syst = sysctl("vfs.bufspace") self.assertAlmostEqual(psutil.virtual_memory().buffers, syst, delta=MEMORY_TOLERANCE) # --- virtual_memory(); tests against muse @unittest.skipIf(not MUSE_AVAILABLE, "muse not installed") def test_muse_vmem_total(self): num = muse('Total') self.assertEqual(psutil.virtual_memory().total, num) @unittest.skipIf(not MUSE_AVAILABLE, "muse not installed") @retry_before_failing() def test_muse_vmem_active(self): num = muse('Active') self.assertAlmostEqual(psutil.virtual_memory().active, num, delta=MEMORY_TOLERANCE) @unittest.skipIf(not MUSE_AVAILABLE, "muse not installed") @retry_before_failing() def test_muse_vmem_inactive(self): num = muse('Inactive') self.assertAlmostEqual(psutil.virtual_memory().inactive, num, delta=MEMORY_TOLERANCE) @unittest.skipIf(not MUSE_AVAILABLE, "muse not installed") @retry_before_failing() def test_muse_vmem_wired(self): num = muse('Wired') self.assertAlmostEqual(psutil.virtual_memory().wired, num, delta=MEMORY_TOLERANCE) @unittest.skipIf(not MUSE_AVAILABLE, "muse not installed") @retry_before_failing() def test_muse_vmem_cached(self): num = muse('Cache') self.assertAlmostEqual(psutil.virtual_memory().cached, num, delta=MEMORY_TOLERANCE) @unittest.skipIf(not MUSE_AVAILABLE, "muse not installed") @retry_before_failing() def test_muse_vmem_free(self): num = muse('Free') self.assertAlmostEqual(psutil.virtual_memory().free, num, delta=MEMORY_TOLERANCE) @unittest.skipIf(not MUSE_AVAILABLE, "muse not installed") @retry_before_failing() def test_muse_vmem_buffers(self): num = muse('Buffer') self.assertAlmostEqual(psutil.virtual_memory().buffers, num, delta=MEMORY_TOLERANCE) def test_cpu_stats_ctx_switches(self): self.assertAlmostEqual(psutil.cpu_stats().ctx_switches, sysctl('vm.stats.sys.v_swtch'), delta=1000) def test_cpu_stats_interrupts(self): self.assertAlmostEqual(psutil.cpu_stats().interrupts, sysctl('vm.stats.sys.v_intr'), delta=1000) def test_cpu_stats_soft_interrupts(self): self.assertAlmostEqual(psutil.cpu_stats().soft_interrupts, sysctl('vm.stats.sys.v_soft'), delta=1000) def test_cpu_stats_syscalls(self): self.assertAlmostEqual(psutil.cpu_stats().syscalls, sysctl('vm.stats.sys.v_syscall'), delta=1000) # def test_cpu_stats_traps(self): # self.assertAlmostEqual(psutil.cpu_stats().traps, # sysctl('vm.stats.sys.v_trap'), delta=1000) # --- others def test_boot_time(self): s = sysctl('sysctl kern.boottime') s = s[s.find(" sec = ") + 7:] s = s[:s.find(',')] btime = int(s) self.assertEqual(btime, psutil.boot_time()) # --- sensors_battery @unittest.skipIf(not HAS_BATTERY, "no battery") def test_sensors_battery(self): def secs2hours(secs): m, s = divmod(secs, 60) h, m = divmod(m, 60) return "%d:%02d" % (h, m) out = sh("acpiconf -i 0") fields = dict([(x.split('\t')[0], x.split('\t')[-1]) for x in out.split("\n")]) metrics = psutil.sensors_battery() percent = int(fields['Remaining capacity:'].replace('%', '')) remaining_time = fields['Remaining time:'] self.assertEqual(metrics.percent, percent) if remaining_time == 'unknown': self.assertEqual(metrics.secsleft, psutil.POWER_TIME_UNLIMITED) else: self.assertEqual(secs2hours(metrics.secsleft), remaining_time) @unittest.skipIf(not HAS_BATTERY, "no battery") def test_sensors_battery_against_sysctl(self): self.assertEqual(psutil.sensors_battery().percent, sysctl("hw.acpi.battery.life")) self.assertEqual(psutil.sensors_battery().power_plugged, sysctl("hw.acpi.acline") == 1) secsleft = psutil.sensors_battery().secsleft if secsleft < 0: self.assertEqual(sysctl("hw.acpi.battery.time"), -1) else: self.assertEqual(secsleft, sysctl("hw.acpi.battery.time") * 60) @unittest.skipIf(HAS_BATTERY, "has battery") def test_sensors_battery_no_battery(self): # If no battery is present one of these calls is supposed # to fail, see: # https://github.com/giampaolo/psutil/issues/1074 with self.assertRaises(RuntimeError): sysctl("hw.acpi.battery.life") sysctl("hw.acpi.battery.time") sysctl("hw.acpi.acline") self.assertIsNone(psutil.sensors_battery()) # ===================================================================== # --- OpenBSD # ===================================================================== @unittest.skipIf(not OPENBSD, "OPENBSD only") class OpenBSDSpecificTestCase(unittest.TestCase): def test_boot_time(self): s = sysctl('kern.boottime') sys_bt = datetime.datetime.strptime(s, "%a %b %d %H:%M:%S %Y") psutil_bt = datetime.datetime.fromtimestamp(psutil.boot_time()) self.assertEqual(sys_bt, psutil_bt) # ===================================================================== # --- NetBSD # ===================================================================== @unittest.skipIf(not NETBSD, "NETBSD only") class NetBSDSpecificTestCase(unittest.TestCase): @staticmethod def parse_meminfo(look_for): with open('/proc/meminfo', 'rb') as f: for line in f: if line.startswith(look_for): return int(line.split()[1]) * 1024 raise ValueError("can't find %s" % look_for) def test_vmem_total(self): self.assertEqual( psutil.virtual_memory().total, self.parse_meminfo("MemTotal:")) def test_vmem_free(self): self.assertAlmostEqual( psutil.virtual_memory().free, self.parse_meminfo("MemFree:"), delta=MEMORY_TOLERANCE) def test_vmem_buffers(self): self.assertAlmostEqual( psutil.virtual_memory().buffers, self.parse_meminfo("Buffers:"), delta=MEMORY_TOLERANCE) def test_vmem_shared(self): self.assertAlmostEqual( psutil.virtual_memory().shared, self.parse_meminfo("MemShared:"), delta=MEMORY_TOLERANCE) def test_swapmem_total(self): self.assertAlmostEqual( psutil.swap_memory().total, self.parse_meminfo("SwapTotal:"), delta=MEMORY_TOLERANCE) def test_swapmem_free(self): self.assertAlmostEqual( psutil.swap_memory().free, self.parse_meminfo("SwapFree:"), delta=MEMORY_TOLERANCE) def test_swapmem_used(self): smem = psutil.swap_memory() self.assertEqual(smem.used, smem.total - smem.free) def test_cpu_stats_interrupts(self): with open('/proc/stat', 'rb') as f: for line in f: if line.startswith(b'intr'): interrupts = int(line.split()[1]) break else: raise ValueError("couldn't find line") self.assertAlmostEqual( psutil.cpu_stats().interrupts, interrupts, delta=1000) def test_cpu_stats_ctx_switches(self): with open('/proc/stat', 'rb') as f: for line in f: if line.startswith(b'ctxt'): ctx_switches = int(line.split()[1]) break else: raise ValueError("couldn't find line") self.assertAlmostEqual( psutil.cpu_stats().ctx_switches, ctx_switches, delta=1000) if __name__ == '__main__': run_test_module_by_name(__file__) PK!zخPPtest_connections.pynu[ # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Tests for net_connections() and Process.connections() APIs.""" import os import socket import textwrap from contextlib import closing from socket import AF_INET from socket import AF_INET6 from socket import SOCK_DGRAM from socket import SOCK_STREAM import psutil from psutil import FREEBSD from psutil import LINUX from psutil import NETBSD from psutil import OPENBSD from psutil import OSX from psutil import POSIX from psutil import SUNOS from psutil import WINDOWS from psutil._common import supports_ipv6 from psutil._compat import PY3 from psutil.tests import AF_UNIX from psutil.tests import bind_socket from psutil.tests import bind_unix_socket from psutil.tests import check_connection_ntuple from psutil.tests import create_sockets from psutil.tests import get_free_port from psutil.tests import HAS_CONNECTIONS_UNIX from psutil.tests import pyrun from psutil.tests import reap_children from psutil.tests import run_test_module_by_name from psutil.tests import safe_rmpath from psutil.tests import skip_on_access_denied from psutil.tests import tcp_socketpair from psutil.tests import TESTFN from psutil.tests import TRAVIS from psutil.tests import unittest from psutil.tests import unix_socket_path from psutil.tests import unix_socketpair from psutil.tests import wait_for_file thisproc = psutil.Process() class Base(object): def setUp(self): if not NETBSD: # NetBSD opens a UNIX socket to /var/log/run. cons = thisproc.connections(kind='all') assert not cons, cons def tearDown(self): safe_rmpath(TESTFN) reap_children() if not NETBSD: # Make sure we closed all resources. # NetBSD opens a UNIX socket to /var/log/run. cons = thisproc.connections(kind='all') assert not cons, cons def get_conn_from_sock(self, sock): cons = thisproc.connections(kind='all') smap = dict([(c.fd, c) for c in cons]) if NETBSD: # NetBSD opens a UNIX socket to /var/log/run # so there may be more connections. return smap[sock.fileno()] else: self.assertEqual(len(cons), 1) if cons[0].fd != -1: self.assertEqual(smap[sock.fileno()].fd, sock.fileno()) return cons[0] def check_socket(self, sock, conn=None): """Given a socket, makes sure it matches the one obtained via psutil. It assumes this process created one connection only (the one supposed to be checked). """ if conn is None: conn = self.get_conn_from_sock(sock) check_connection_ntuple(conn) # fd, family, type if conn.fd != -1: self.assertEqual(conn.fd, sock.fileno()) self.assertEqual(conn.family, sock.family) # see: http://bugs.python.org/issue30204 self.assertEqual( conn.type, sock.getsockopt(socket.SOL_SOCKET, socket.SO_TYPE)) # local address laddr = sock.getsockname() if not laddr and PY3 and isinstance(laddr, bytes): # See: http://bugs.python.org/issue30205 laddr = laddr.decode() if sock.family == AF_INET6: laddr = laddr[:2] if sock.family == AF_UNIX and OPENBSD: # No addresses are set for UNIX sockets on OpenBSD. pass else: self.assertEqual(conn.laddr, laddr) # XXX Solaris can't retrieve system-wide UNIX sockets if sock.family == AF_UNIX and HAS_CONNECTIONS_UNIX: cons = thisproc.connections(kind='all') self.compare_procsys_connections(os.getpid(), cons) return conn def compare_procsys_connections(self, pid, proc_cons, kind='all'): """Given a process PID and its list of connections compare those against system-wide connections retrieved via psutil.net_connections. """ try: sys_cons = psutil.net_connections(kind=kind) except psutil.AccessDenied: # On OSX, system-wide connections are retrieved by iterating # over all processes if OSX: return else: raise # Filter for this proc PID and exlucde PIDs from the tuple. sys_cons = [c[:-1] for c in sys_cons if c.pid == pid] sys_cons.sort() proc_cons.sort() self.assertEqual(proc_cons, sys_cons) # ===================================================================== # --- Test unconnected sockets # ===================================================================== class TestUnconnectedSockets(Base, unittest.TestCase): """Tests sockets which are open but not connected to anything.""" def test_tcp_v4(self): addr = ("127.0.0.1", get_free_port()) with closing(bind_socket(AF_INET, SOCK_STREAM, addr=addr)) as sock: conn = self.check_socket(sock) assert not conn.raddr self.assertEqual(conn.status, psutil.CONN_LISTEN) @unittest.skipIf(not supports_ipv6(), "IPv6 not supported") def test_tcp_v6(self): addr = ("::1", get_free_port()) with closing(bind_socket(AF_INET6, SOCK_STREAM, addr=addr)) as sock: conn = self.check_socket(sock) assert not conn.raddr self.assertEqual(conn.status, psutil.CONN_LISTEN) def test_udp_v4(self): addr = ("127.0.0.1", get_free_port()) with closing(bind_socket(AF_INET, SOCK_DGRAM, addr=addr)) as sock: conn = self.check_socket(sock) assert not conn.raddr self.assertEqual(conn.status, psutil.CONN_NONE) @unittest.skipIf(not supports_ipv6(), "IPv6 not supported") def test_udp_v6(self): addr = ("::1", get_free_port()) with closing(bind_socket(AF_INET6, SOCK_DGRAM, addr=addr)) as sock: conn = self.check_socket(sock) assert not conn.raddr self.assertEqual(conn.status, psutil.CONN_NONE) @unittest.skipIf(not POSIX, 'POSIX only') def test_unix_tcp(self): with unix_socket_path() as name: with closing(bind_unix_socket(name, type=SOCK_STREAM)) as sock: conn = self.check_socket(sock) assert not conn.raddr self.assertEqual(conn.status, psutil.CONN_NONE) @unittest.skipIf(not POSIX, 'POSIX only') def test_unix_udp(self): with unix_socket_path() as name: with closing(bind_unix_socket(name, type=SOCK_STREAM)) as sock: conn = self.check_socket(sock) assert not conn.raddr self.assertEqual(conn.status, psutil.CONN_NONE) # ===================================================================== # --- Test connected sockets # ===================================================================== class TestConnectedSocketPairs(Base, unittest.TestCase): """Test socket pairs which are are actually connected to each other. """ # On SunOS, even after we close() it, the server socket stays around # in TIME_WAIT state. @unittest.skipIf(SUNOS, "unreliable on SUONS") def test_tcp(self): addr = ("127.0.0.1", get_free_port()) assert not thisproc.connections(kind='tcp4') server, client = tcp_socketpair(AF_INET, addr=addr) try: cons = thisproc.connections(kind='tcp4') self.assertEqual(len(cons), 2) self.assertEqual(cons[0].status, psutil.CONN_ESTABLISHED) self.assertEqual(cons[1].status, psutil.CONN_ESTABLISHED) # May not be fast enough to change state so it stays # commenteed. # client.close() # cons = thisproc.connections(kind='all') # self.assertEqual(len(cons), 1) # self.assertEqual(cons[0].status, psutil.CONN_CLOSE_WAIT) finally: server.close() client.close() @unittest.skipIf(not POSIX, 'POSIX only') def test_unix(self): with unix_socket_path() as name: server, client = unix_socketpair(name) try: cons = thisproc.connections(kind='unix') assert not (cons[0].laddr and cons[0].raddr) assert not (cons[1].laddr and cons[1].raddr) if NETBSD: # On NetBSD creating a UNIX socket will cause # a UNIX connection to /var/run/log. cons = [c for c in cons if c.raddr != '/var/run/log'] self.assertEqual(len(cons), 2) if LINUX or FREEBSD or SUNOS: # remote path is never set self.assertEqual(cons[0].raddr, "") self.assertEqual(cons[1].raddr, "") # one local address should though self.assertEqual(name, cons[0].laddr or cons[1].laddr) elif OPENBSD: # No addresses whatsoever here. for addr in (cons[0].laddr, cons[0].raddr, cons[1].laddr, cons[1].raddr): self.assertEqual(addr, "") else: # On other systems either the laddr or raddr # of both peers are set. self.assertEqual(cons[0].laddr or cons[1].laddr, name) self.assertEqual(cons[0].raddr or cons[1].raddr, name) finally: server.close() client.close() @skip_on_access_denied(only_if=OSX) def test_combos(self): def check_conn(proc, conn, family, type, laddr, raddr, status, kinds): all_kinds = ("all", "inet", "inet4", "inet6", "tcp", "tcp4", "tcp6", "udp", "udp4", "udp6") check_connection_ntuple(conn) self.assertEqual(conn.family, family) self.assertEqual(conn.type, type) self.assertEqual(conn.laddr, laddr) self.assertEqual(conn.raddr, raddr) self.assertEqual(conn.status, status) for kind in all_kinds: cons = proc.connections(kind=kind) if kind in kinds: assert cons else: assert not cons, cons # compare against system-wide connections # XXX Solaris can't retrieve system-wide UNIX # sockets. if HAS_CONNECTIONS_UNIX: self.compare_procsys_connections(proc.pid, [conn]) tcp_template = textwrap.dedent(""" import socket, time s = socket.socket($family, socket.SOCK_STREAM) s.bind(('$addr', 0)) s.listen(1) with open('$testfn', 'w') as f: f.write(str(s.getsockname()[:2])) time.sleep(60) """) udp_template = textwrap.dedent(""" import socket, time s = socket.socket($family, socket.SOCK_DGRAM) s.bind(('$addr', 0)) with open('$testfn', 'w') as f: f.write(str(s.getsockname()[:2])) time.sleep(60) """) from string import Template testfile = os.path.basename(TESTFN) tcp4_template = Template(tcp_template).substitute( family=int(AF_INET), addr="127.0.0.1", testfn=testfile) udp4_template = Template(udp_template).substitute( family=int(AF_INET), addr="127.0.0.1", testfn=testfile) tcp6_template = Template(tcp_template).substitute( family=int(AF_INET6), addr="::1", testfn=testfile) udp6_template = Template(udp_template).substitute( family=int(AF_INET6), addr="::1", testfn=testfile) # launch various subprocess instantiating a socket of various # families and types to enrich psutil results tcp4_proc = pyrun(tcp4_template) tcp4_addr = eval(wait_for_file(testfile)) udp4_proc = pyrun(udp4_template) udp4_addr = eval(wait_for_file(testfile)) if supports_ipv6(): tcp6_proc = pyrun(tcp6_template) tcp6_addr = eval(wait_for_file(testfile)) udp6_proc = pyrun(udp6_template) udp6_addr = eval(wait_for_file(testfile)) else: tcp6_proc = None udp6_proc = None tcp6_addr = None udp6_addr = None for p in thisproc.children(): cons = p.connections() self.assertEqual(len(cons), 1) for conn in cons: # TCP v4 if p.pid == tcp4_proc.pid: check_conn(p, conn, AF_INET, SOCK_STREAM, tcp4_addr, (), psutil.CONN_LISTEN, ("all", "inet", "inet4", "tcp", "tcp4")) # UDP v4 elif p.pid == udp4_proc.pid: check_conn(p, conn, AF_INET, SOCK_DGRAM, udp4_addr, (), psutil.CONN_NONE, ("all", "inet", "inet4", "udp", "udp4")) # TCP v6 elif p.pid == getattr(tcp6_proc, "pid", None): check_conn(p, conn, AF_INET6, SOCK_STREAM, tcp6_addr, (), psutil.CONN_LISTEN, ("all", "inet", "inet6", "tcp", "tcp6")) # UDP v6 elif p.pid == getattr(udp6_proc, "pid", None): check_conn(p, conn, AF_INET6, SOCK_DGRAM, udp6_addr, (), psutil.CONN_NONE, ("all", "inet", "inet6", "udp", "udp6")) # err self.assertRaises(ValueError, p.connections, kind='???') def test_multi_sockets_filtering(self): with create_sockets() as socks: cons = thisproc.connections(kind='all') self.assertEqual(len(cons), len(socks)) # tcp cons = thisproc.connections(kind='tcp') self.assertEqual(len(cons), 2 if supports_ipv6() else 1) for conn in cons: self.assertIn(conn.family, (AF_INET, AF_INET6)) self.assertEqual(conn.type, SOCK_STREAM) # tcp4 cons = thisproc.connections(kind='tcp4') self.assertEqual(len(cons), 1) self.assertEqual(cons[0].family, AF_INET) self.assertEqual(cons[0].type, SOCK_STREAM) # tcp6 if supports_ipv6(): cons = thisproc.connections(kind='tcp6') self.assertEqual(len(cons), 1) self.assertEqual(cons[0].family, AF_INET6) self.assertEqual(cons[0].type, SOCK_STREAM) # udp cons = thisproc.connections(kind='udp') self.assertEqual(len(cons), 2 if supports_ipv6() else 1) for conn in cons: self.assertIn(conn.family, (AF_INET, AF_INET6)) self.assertEqual(conn.type, SOCK_DGRAM) # udp4 cons = thisproc.connections(kind='udp4') self.assertEqual(len(cons), 1) self.assertEqual(cons[0].family, AF_INET) self.assertEqual(cons[0].type, SOCK_DGRAM) # udp6 if supports_ipv6(): cons = thisproc.connections(kind='udp6') self.assertEqual(len(cons), 1) self.assertEqual(cons[0].family, AF_INET6) self.assertEqual(cons[0].type, SOCK_DGRAM) # inet cons = thisproc.connections(kind='inet') self.assertEqual(len(cons), 4 if supports_ipv6() else 2) for conn in cons: self.assertIn(conn.family, (AF_INET, AF_INET6)) self.assertIn(conn.type, (SOCK_STREAM, SOCK_DGRAM)) # inet6 if supports_ipv6(): cons = thisproc.connections(kind='inet6') self.assertEqual(len(cons), 2) for conn in cons: self.assertEqual(conn.family, AF_INET6) self.assertIn(conn.type, (SOCK_STREAM, SOCK_DGRAM)) # unix if HAS_CONNECTIONS_UNIX: cons = thisproc.connections(kind='unix') self.assertEqual(len(cons), 3) for conn in cons: self.assertEqual(conn.family, AF_UNIX) self.assertIn(conn.type, (SOCK_STREAM, SOCK_DGRAM)) # ===================================================================== # --- Miscellaneous tests # ===================================================================== class TestSystemWideConnections(Base, unittest.TestCase): """Tests for net_connections().""" @skip_on_access_denied() def test_it(self): def check(cons, families, types_): AF_UNIX = getattr(socket, 'AF_UNIX', object()) for conn in cons: self.assertIn(conn.family, families, msg=conn) if conn.family != AF_UNIX: self.assertIn(conn.type, types_, msg=conn) check_connection_ntuple(conn) with create_sockets(): from psutil._common import conn_tmap for kind, groups in conn_tmap.items(): # XXX: SunOS does not retrieve UNIX sockets. if kind == 'unix' and not HAS_CONNECTIONS_UNIX: continue families, types_ = groups cons = psutil.net_connections(kind) self.assertEqual(len(cons), len(set(cons))) check(cons, families, types_) self.assertRaises(ValueError, psutil.net_connections, kind='???') @skip_on_access_denied() def test_multi_socks(self): with create_sockets() as socks: cons = [x for x in psutil.net_connections(kind='all') if x.pid == os.getpid()] self.assertEqual(len(cons), len(socks)) @skip_on_access_denied() # See: https://travis-ci.org/giampaolo/psutil/jobs/237566297 @unittest.skipIf(OSX and TRAVIS, "unreliable on OSX + TRAVIS") def test_multi_sockets_procs(self): # Creates multiple sub processes, each creating different # sockets. For each process check that proc.connections() # and net_connections() return the same results. # This is done mainly to check whether net_connections()'s # pid is properly set, see: # https://github.com/giampaolo/psutil/issues/1013 with create_sockets() as socks: expected = len(socks) pids = [] times = 10 for i in range(times): fname = os.path.realpath(TESTFN) + str(i) src = textwrap.dedent("""\ import time, os from psutil.tests import create_sockets with create_sockets(): with open('%s', 'w') as f: f.write(str(os.getpid())) time.sleep(60) """ % fname) sproc = pyrun(src) pids.append(sproc.pid) self.addCleanup(safe_rmpath, fname) # sync for i in range(times): fname = TESTFN + str(i) wait_for_file(fname) syscons = [x for x in psutil.net_connections(kind='all') if x.pid in pids] for pid in pids: self.assertEqual(len([x for x in syscons if x.pid == pid]), expected) p = psutil.Process(pid) self.assertEqual(len(p.connections('all')), expected) # ===================================================================== # --- Miscellaneous tests # ===================================================================== class TestMisc(unittest.TestCase): def test_connection_constants(self): ints = [] strs = [] for name in dir(psutil): if name.startswith('CONN_'): num = getattr(psutil, name) str_ = str(num) assert str_.isupper(), str_ self.assertNotIn(str, strs) self.assertNotIn(num, ints) ints.append(num) strs.append(str_) if SUNOS: psutil.CONN_IDLE psutil.CONN_BOUND if WINDOWS: psutil.CONN_DELETE_TCB if __name__ == '__main__': run_test_module_by_name(__file__) PK!2^2^test_contracts.pynu[ # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Contracts tests. These tests mainly check API sanity in terms of returned types and APIs availability. Some of these are duplicates of tests test_system.py and test_process.py """ import errno import os import stat import time import traceback import warnings from contextlib import closing from psutil import AIX from psutil import BSD from psutil import FREEBSD from psutil import LINUX from psutil import NETBSD from psutil import OPENBSD from psutil import OSX from psutil import POSIX from psutil import SUNOS from psutil import WINDOWS from psutil._compat import callable from psutil._compat import long from psutil.tests import bind_unix_socket from psutil.tests import check_connection_ntuple from psutil.tests import get_kernel_version from psutil.tests import HAS_CONNECTIONS_UNIX from psutil.tests import HAS_RLIMIT from psutil.tests import HAS_SENSORS_FANS from psutil.tests import HAS_SENSORS_TEMPERATURES from psutil.tests import is_namedtuple from psutil.tests import run_test_module_by_name from psutil.tests import safe_rmpath from psutil.tests import skip_on_access_denied from psutil.tests import TESTFN from psutil.tests import unittest from psutil.tests import unix_socket_path from psutil.tests import VALID_PROC_STATUSES from psutil.tests import warn import psutil # =================================================================== # --- APIs availability # =================================================================== class TestAvailability(unittest.TestCase): """Make sure code reflects what doc promises in terms of APIs availability. """ def test_cpu_affinity(self): hasit = LINUX or WINDOWS or FREEBSD self.assertEqual(hasattr(psutil.Process, "cpu_affinity"), hasit) def test_win_service(self): self.assertEqual(hasattr(psutil, "win_service_iter"), WINDOWS) self.assertEqual(hasattr(psutil, "win_service_get"), WINDOWS) def test_PROCFS_PATH(self): self.assertEqual(hasattr(psutil, "PROCFS_PATH"), LINUX or SUNOS or AIX) def test_win_priority(self): ae = self.assertEqual ae(hasattr(psutil, "ABOVE_NORMAL_PRIORITY_CLASS"), WINDOWS) ae(hasattr(psutil, "BELOW_NORMAL_PRIORITY_CLASS"), WINDOWS) ae(hasattr(psutil, "HIGH_PRIORITY_CLASS"), WINDOWS) ae(hasattr(psutil, "IDLE_PRIORITY_CLASS"), WINDOWS) ae(hasattr(psutil, "NORMAL_PRIORITY_CLASS"), WINDOWS) ae(hasattr(psutil, "REALTIME_PRIORITY_CLASS"), WINDOWS) def test_linux_ioprio(self): ae = self.assertEqual ae(hasattr(psutil, "IOPRIO_CLASS_NONE"), LINUX) ae(hasattr(psutil, "IOPRIO_CLASS_RT"), LINUX) ae(hasattr(psutil, "IOPRIO_CLASS_BE"), LINUX) ae(hasattr(psutil, "IOPRIO_CLASS_IDLE"), LINUX) def test_linux_rlimit(self): ae = self.assertEqual hasit = LINUX and get_kernel_version() >= (2, 6, 36) ae(hasattr(psutil.Process, "rlimit"), hasit) ae(hasattr(psutil, "RLIM_INFINITY"), hasit) ae(hasattr(psutil, "RLIMIT_AS"), hasit) ae(hasattr(psutil, "RLIMIT_CORE"), hasit) ae(hasattr(psutil, "RLIMIT_CPU"), hasit) ae(hasattr(psutil, "RLIMIT_DATA"), hasit) ae(hasattr(psutil, "RLIMIT_FSIZE"), hasit) ae(hasattr(psutil, "RLIMIT_LOCKS"), hasit) ae(hasattr(psutil, "RLIMIT_MEMLOCK"), hasit) ae(hasattr(psutil, "RLIMIT_NOFILE"), hasit) ae(hasattr(psutil, "RLIMIT_NPROC"), hasit) ae(hasattr(psutil, "RLIMIT_RSS"), hasit) ae(hasattr(psutil, "RLIMIT_STACK"), hasit) hasit = LINUX and get_kernel_version() >= (3, 0) ae(hasattr(psutil, "RLIMIT_MSGQUEUE"), hasit) ae(hasattr(psutil, "RLIMIT_NICE"), hasit) ae(hasattr(psutil, "RLIMIT_RTPRIO"), hasit) ae(hasattr(psutil, "RLIMIT_RTTIME"), hasit) ae(hasattr(psutil, "RLIMIT_SIGPENDING"), hasit) def test_cpu_freq(self): linux = (LINUX and (os.path.exists("/sys/devices/system/cpu/cpufreq") or os.path.exists("/sys/devices/system/cpu/cpu0/cpufreq"))) self.assertEqual(hasattr(psutil, "cpu_freq"), linux or OSX or WINDOWS) def test_sensors_temperatures(self): self.assertEqual(hasattr(psutil, "sensors_temperatures"), LINUX) def test_sensors_fans(self): self.assertEqual(hasattr(psutil, "sensors_fans"), LINUX) def test_battery(self): self.assertEqual(hasattr(psutil, "sensors_battery"), LINUX or WINDOWS or FREEBSD or OSX) def test_proc_environ(self): self.assertEqual(hasattr(psutil.Process, "environ"), LINUX or OSX or WINDOWS) def test_proc_uids(self): self.assertEqual(hasattr(psutil.Process, "uids"), POSIX) def test_proc_gids(self): self.assertEqual(hasattr(psutil.Process, "uids"), POSIX) def test_proc_terminal(self): self.assertEqual(hasattr(psutil.Process, "terminal"), POSIX) def test_proc_ionice(self): self.assertEqual(hasattr(psutil.Process, "ionice"), LINUX or WINDOWS) def test_proc_rlimit(self): self.assertEqual(hasattr(psutil.Process, "rlimit"), LINUX) def test_proc_io_counters(self): hasit = hasattr(psutil.Process, "io_counters") self.assertEqual(hasit, False if OSX or SUNOS else True) def test_proc_num_fds(self): self.assertEqual(hasattr(psutil.Process, "num_fds"), POSIX) def test_proc_num_handles(self): self.assertEqual(hasattr(psutil.Process, "num_handles"), WINDOWS) def test_proc_cpu_affinity(self): self.assertEqual(hasattr(psutil.Process, "cpu_affinity"), LINUX or WINDOWS or FREEBSD) def test_proc_cpu_num(self): self.assertEqual(hasattr(psutil.Process, "cpu_num"), LINUX or FREEBSD or SUNOS) def test_proc_memory_maps(self): hasit = hasattr(psutil.Process, "memory_maps") self.assertEqual(hasit, False if OPENBSD or NETBSD or AIX else True) # =================================================================== # --- Test deprecations # =================================================================== class TestDeprecations(unittest.TestCase): def test_memory_info_ex(self): with warnings.catch_warnings(record=True) as ws: psutil.Process().memory_info_ex() w = ws[0] self.assertIsInstance(w.category(), FutureWarning) self.assertIn("memory_info_ex() is deprecated", str(w.message)) self.assertIn("use memory_info() instead", str(w.message)) # =================================================================== # --- System API types # =================================================================== class TestSystem(unittest.TestCase): """Check the return types of system related APIs. Mainly we want to test we never return unicode on Python 2, see: https://github.com/giampaolo/psutil/issues/1039 """ @classmethod def setUpClass(cls): cls.proc = psutil.Process() def tearDown(self): safe_rmpath(TESTFN) def test_cpu_times(self): # Duplicate of test_system.py. Keep it anyway. ret = psutil.cpu_times() assert is_namedtuple(ret) for n in ret: self.assertIsInstance(n, float) self.assertGreaterEqual(n, 0) def test_io_counters(self): # Duplicate of test_system.py. Keep it anyway. for k in psutil.disk_io_counters(perdisk=True): self.assertIsInstance(k, str) def test_disk_partitions(self): # Duplicate of test_system.py. Keep it anyway. for disk in psutil.disk_partitions(): self.assertIsInstance(disk.device, str) self.assertIsInstance(disk.mountpoint, str) self.assertIsInstance(disk.fstype, str) self.assertIsInstance(disk.opts, str) @unittest.skipIf(not POSIX, 'POSIX only') @unittest.skipIf(not HAS_CONNECTIONS_UNIX, "can't list UNIX sockets") @skip_on_access_denied(only_if=OSX) def test_net_connections(self): with unix_socket_path() as name: with closing(bind_unix_socket(name)): cons = psutil.net_connections(kind='unix') assert cons for conn in cons: self.assertIsInstance(conn.laddr, str) def test_net_if_addrs(self): # Duplicate of test_system.py. Keep it anyway. for ifname, addrs in psutil.net_if_addrs().items(): self.assertIsInstance(ifname, str) for addr in addrs: self.assertIsInstance(addr.address, str) self.assertIsInstance(addr.netmask, (str, type(None))) self.assertIsInstance(addr.broadcast, (str, type(None))) def test_net_if_stats(self): # Duplicate of test_system.py. Keep it anyway. for ifname, _ in psutil.net_if_stats().items(): self.assertIsInstance(ifname, str) def test_net_io_counters(self): # Duplicate of test_system.py. Keep it anyway. for ifname, _ in psutil.net_io_counters(pernic=True).items(): self.assertIsInstance(ifname, str) @unittest.skipIf(not HAS_SENSORS_FANS, "not supported") def test_sensors_fans(self): # Duplicate of test_system.py. Keep it anyway. for name, units in psutil.sensors_fans().items(): self.assertIsInstance(name, str) for unit in units: self.assertIsInstance(unit.label, str) @unittest.skipIf(not HAS_SENSORS_TEMPERATURES, "not supported") def test_sensors_temperatures(self): # Duplicate of test_system.py. Keep it anyway. for name, units in psutil.sensors_temperatures().items(): self.assertIsInstance(name, str) for unit in units: self.assertIsInstance(unit.label, str) def test_users(self): # Duplicate of test_system.py. Keep it anyway. for user in psutil.users(): self.assertIsInstance(user.name, str) self.assertIsInstance(user.terminal, (str, type(None))) self.assertIsInstance(user.host, (str, type(None))) self.assertIsInstance(user.pid, (int, type(None))) # =================================================================== # --- Featch all processes test # =================================================================== class TestFetchAllProcesses(unittest.TestCase): """Test which iterates over all running processes and performs some sanity checks against Process API's returned values. """ def setUp(self): if POSIX: import pwd import grp users = pwd.getpwall() groups = grp.getgrall() self.all_uids = set([x.pw_uid for x in users]) self.all_usernames = set([x.pw_name for x in users]) self.all_gids = set([x.gr_gid for x in groups]) def test_fetch_all(self): valid_procs = 0 excluded_names = set([ 'send_signal', 'suspend', 'resume', 'terminate', 'kill', 'wait', 'as_dict', 'parent', 'children', 'memory_info_ex', 'oneshot', ]) if LINUX and not HAS_RLIMIT: excluded_names.add('rlimit') attrs = [] for name in dir(psutil.Process): if name.startswith("_"): continue if name in excluded_names: continue attrs.append(name) default = object() failures = [] for p in psutil.process_iter(): with p.oneshot(): for name in attrs: ret = default try: args = () kwargs = {} attr = getattr(p, name, None) if attr is not None and callable(attr): if name == 'rlimit': args = (psutil.RLIMIT_NOFILE,) elif name == 'memory_maps': kwargs = {'grouped': False} ret = attr(*args, **kwargs) else: ret = attr valid_procs += 1 except NotImplementedError: msg = "%r was skipped because not implemented" % ( self.__class__.__name__ + '.test_' + name) warn(msg) except (psutil.NoSuchProcess, psutil.AccessDenied) as err: self.assertEqual(err.pid, p.pid) if err.name: # make sure exception's name attr is set # with the actual process name self.assertEqual(err.name, p.name()) assert str(err) assert err.msg except Exception as err: s = '\n' + '=' * 70 + '\n' s += "FAIL: test_%s (proc=%s" % (name, p) if ret != default: s += ", ret=%s)" % repr(ret) s += ')\n' s += '-' * 70 s += "\n%s" % traceback.format_exc() s = "\n".join((" " * 4) + i for i in s.splitlines()) s += '\n' failures.append(s) break else: if ret not in (0, 0.0, [], None, '', {}): assert ret, ret meth = getattr(self, name) meth(ret, p) if failures: self.fail(''.join(failures)) # we should always have a non-empty list, not including PID 0 etc. # special cases. assert valid_procs def cmdline(self, ret, proc): self.assertIsInstance(ret, list) for part in ret: self.assertIsInstance(part, str) def exe(self, ret, proc): self.assertIsInstance(ret, (str, type(None))) if not ret: self.assertEqual(ret, '') else: assert os.path.isabs(ret), ret # Note: os.stat() may return False even if the file is there # hence we skip the test, see: # http://stackoverflow.com/questions/3112546/os-path-exists-lies if POSIX and os.path.isfile(ret): if hasattr(os, 'access') and hasattr(os, "X_OK"): # XXX may fail on OSX assert os.access(ret, os.X_OK) def pid(self, ret, proc): self.assertIsInstance(ret, int) self.assertGreaterEqual(ret, 0) def ppid(self, ret, proc): self.assertIsInstance(ret, (int, long)) self.assertGreaterEqual(ret, 0) def name(self, ret, proc): self.assertIsInstance(ret, str) # on AIX, "" processes don't have names if not AIX: assert ret def create_time(self, ret, proc): self.assertIsInstance(ret, float) try: self.assertGreaterEqual(ret, 0) except AssertionError: # XXX if OPENBSD and proc.status() == psutil.STATUS_ZOMBIE: pass else: raise # this can't be taken for granted on all platforms # self.assertGreaterEqual(ret, psutil.boot_time()) # make sure returned value can be pretty printed # with strftime time.strftime("%Y %m %d %H:%M:%S", time.localtime(ret)) def uids(self, ret, proc): assert is_namedtuple(ret) for uid in ret: self.assertIsInstance(uid, int) self.assertGreaterEqual(uid, 0) self.assertIn(uid, self.all_uids) def gids(self, ret, proc): assert is_namedtuple(ret) # note: testing all gids as above seems not to be reliable for # gid == 30 (nodoby); not sure why. for gid in ret: self.assertIsInstance(gid, int) if not OSX and not NETBSD: self.assertGreaterEqual(gid, 0) self.assertIn(gid, self.all_gids) def username(self, ret, proc): self.assertIsInstance(ret, str) assert ret if POSIX: self.assertIn(ret, self.all_usernames) def status(self, ret, proc): self.assertIsInstance(ret, str) assert ret self.assertNotEqual(ret, '?') # XXX self.assertIn(ret, VALID_PROC_STATUSES) def io_counters(self, ret, proc): assert is_namedtuple(ret) for field in ret: self.assertIsInstance(field, (int, long)) if field != -1: self.assertGreaterEqual(field, 0) def ionice(self, ret, proc): if POSIX: assert is_namedtuple(ret) for field in ret: self.assertIsInstance(field, int) if LINUX: self.assertGreaterEqual(ret.ioclass, 0) self.assertGreaterEqual(ret.value, 0) else: self.assertGreaterEqual(ret, 0) self.assertIn(ret, (0, 1, 2)) def num_threads(self, ret, proc): self.assertIsInstance(ret, int) self.assertGreaterEqual(ret, 1) def threads(self, ret, proc): self.assertIsInstance(ret, list) for t in ret: assert is_namedtuple(t) self.assertGreaterEqual(t.id, 0) self.assertGreaterEqual(t.user_time, 0) self.assertGreaterEqual(t.system_time, 0) for field in t: self.assertIsInstance(field, (int, float)) def cpu_times(self, ret, proc): assert is_namedtuple(ret) for n in ret: self.assertIsInstance(n, float) self.assertGreaterEqual(n, 0) # TODO: check ntuple fields def cpu_percent(self, ret, proc): self.assertIsInstance(ret, float) assert 0.0 <= ret <= 100.0, ret def cpu_num(self, ret, proc): self.assertIsInstance(ret, int) if FREEBSD and ret == -1: return self.assertGreaterEqual(ret, 0) if psutil.cpu_count() == 1: self.assertEqual(ret, 0) self.assertIn(ret, list(range(psutil.cpu_count()))) def memory_info(self, ret, proc): assert is_namedtuple(ret) for value in ret: self.assertIsInstance(value, (int, long)) self.assertGreaterEqual(value, 0) if POSIX and not AIX and ret.vms != 0: # VMS is always supposed to be the highest for name in ret._fields: if name != 'vms': value = getattr(ret, name) self.assertGreater(ret.vms, value, msg=ret) elif WINDOWS: self.assertGreaterEqual(ret.peak_wset, ret.wset) self.assertGreaterEqual(ret.peak_paged_pool, ret.paged_pool) self.assertGreaterEqual(ret.peak_nonpaged_pool, ret.nonpaged_pool) self.assertGreaterEqual(ret.peak_pagefile, ret.pagefile) def memory_full_info(self, ret, proc): assert is_namedtuple(ret) total = psutil.virtual_memory().total for name in ret._fields: value = getattr(ret, name) self.assertIsInstance(value, (int, long)) self.assertGreaterEqual(value, 0, msg=(name, value)) self.assertLessEqual(value, total, msg=(name, value, total)) if LINUX: self.assertGreaterEqual(ret.pss, ret.uss) def open_files(self, ret, proc): self.assertIsInstance(ret, list) for f in ret: self.assertIsInstance(f.fd, int) self.assertIsInstance(f.path, str) if WINDOWS: self.assertEqual(f.fd, -1) elif LINUX: self.assertIsInstance(f.position, int) self.assertIsInstance(f.mode, str) self.assertIsInstance(f.flags, int) self.assertGreaterEqual(f.position, 0) self.assertIn(f.mode, ('r', 'w', 'a', 'r+', 'a+')) self.assertGreater(f.flags, 0) elif BSD and not f.path: # XXX see: https://github.com/giampaolo/psutil/issues/595 continue assert os.path.isabs(f.path), f assert os.path.isfile(f.path), f def num_fds(self, ret, proc): self.assertIsInstance(ret, int) self.assertGreaterEqual(ret, 0) def connections(self, ret, proc): self.assertEqual(len(ret), len(set(ret))) for conn in ret: check_connection_ntuple(conn) def cwd(self, ret, proc): if ret: # 'ret' can be None or empty self.assertIsInstance(ret, str) assert os.path.isabs(ret), ret try: st = os.stat(ret) except OSError as err: if WINDOWS and err.errno in \ psutil._psplatform.ACCESS_DENIED_SET: pass # directory has been removed in mean time elif err.errno != errno.ENOENT: raise else: assert stat.S_ISDIR(st.st_mode) def memory_percent(self, ret, proc): self.assertIsInstance(ret, float) assert 0 <= ret <= 100, ret def is_running(self, ret, proc): self.assertIsInstance(ret, bool) def cpu_affinity(self, ret, proc): self.assertIsInstance(ret, list) assert ret != [], ret cpus = range(psutil.cpu_count()) for n in ret: self.assertIsInstance(n, int) self.assertIn(n, cpus) def terminal(self, ret, proc): self.assertIsInstance(ret, (str, type(None))) if ret is not None: assert os.path.isabs(ret), ret assert os.path.exists(ret), ret def memory_maps(self, ret, proc): for nt in ret: self.assertIsInstance(nt.addr, str) self.assertIsInstance(nt.perms, str) self.assertIsInstance(nt.path, str) for fname in nt._fields: value = getattr(nt, fname) if fname == 'path': if not value.startswith('['): assert os.path.isabs(nt.path), nt.path # commented as on Linux we might get # '/foo/bar (deleted)' # assert os.path.exists(nt.path), nt.path elif fname in ('addr', 'perms'): assert value else: self.assertIsInstance(value, (int, long)) self.assertGreaterEqual(value, 0) def num_handles(self, ret, proc): self.assertIsInstance(ret, int) self.assertGreaterEqual(ret, 0) def nice(self, ret, proc): self.assertIsInstance(ret, int) if POSIX: assert -20 <= ret <= 20, ret else: priorities = [getattr(psutil, x) for x in dir(psutil) if x.endswith('_PRIORITY_CLASS')] self.assertIn(ret, priorities) def num_ctx_switches(self, ret, proc): assert is_namedtuple(ret) for value in ret: self.assertIsInstance(value, (int, long)) self.assertGreaterEqual(value, 0) def rlimit(self, ret, proc): self.assertIsInstance(ret, tuple) self.assertEqual(len(ret), 2) self.assertGreaterEqual(ret[0], -1) self.assertGreaterEqual(ret[1], -1) def environ(self, ret, proc): self.assertIsInstance(ret, dict) for k, v in ret.items(): self.assertIsInstance(k, str) self.assertIsInstance(v, str) if __name__ == '__main__': run_test_module_by_name(__file__) PK!H99test_process.pynu[ # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Tests for psutil.Process class.""" import collections import errno import getpass import itertools import os import signal import socket import subprocess import sys import tempfile import textwrap import time import types import psutil from psutil import AIX from psutil import BSD from psutil import LINUX from psutil import NETBSD from psutil import OPENBSD from psutil import OSX from psutil import POSIX from psutil import SUNOS from psutil import WINDOWS from psutil._compat import long from psutil._compat import PY3 from psutil.tests import APPVEYOR from psutil.tests import call_until from psutil.tests import copyload_shared_lib from psutil.tests import create_exe from psutil.tests import create_proc_children_pair from psutil.tests import create_zombie_proc from psutil.tests import enum from psutil.tests import get_test_subprocess from psutil.tests import get_winver from psutil.tests import HAS_CPU_AFFINITY from psutil.tests import HAS_ENVIRON from psutil.tests import HAS_IONICE from psutil.tests import HAS_MEMORY_MAPS from psutil.tests import HAS_PROC_CPU_NUM from psutil.tests import HAS_PROC_IO_COUNTERS from psutil.tests import HAS_RLIMIT from psutil.tests import HAS_THREADS from psutil.tests import mock from psutil.tests import PYPY from psutil.tests import PYTHON_EXE from psutil.tests import reap_children from psutil.tests import retry_before_failing from psutil.tests import run_test_module_by_name from psutil.tests import safe_rmpath from psutil.tests import sh from psutil.tests import skip_on_access_denied from psutil.tests import skip_on_not_implemented from psutil.tests import TESTFILE_PREFIX from psutil.tests import TESTFN from psutil.tests import ThreadTask from psutil.tests import TRAVIS from psutil.tests import unittest from psutil.tests import wait_for_pid from psutil.tests import WIN_VISTA # =================================================================== # --- psutil.Process class tests # =================================================================== class TestProcess(unittest.TestCase): """Tests for psutil.Process class.""" def setUp(self): safe_rmpath(TESTFN) def tearDown(self): reap_children() def test_pid(self): p = psutil.Process() self.assertEqual(p.pid, os.getpid()) sproc = get_test_subprocess() self.assertEqual(psutil.Process(sproc.pid).pid, sproc.pid) with self.assertRaises(AttributeError): p.pid = 33 def test_kill(self): sproc = get_test_subprocess() test_pid = sproc.pid p = psutil.Process(test_pid) p.kill() sig = p.wait() self.assertFalse(psutil.pid_exists(test_pid)) if POSIX: self.assertEqual(sig, -signal.SIGKILL) def test_terminate(self): sproc = get_test_subprocess() test_pid = sproc.pid p = psutil.Process(test_pid) p.terminate() sig = p.wait() self.assertFalse(psutil.pid_exists(test_pid)) if POSIX: self.assertEqual(sig, -signal.SIGTERM) def test_send_signal(self): sig = signal.SIGKILL if POSIX else signal.SIGTERM sproc = get_test_subprocess() p = psutil.Process(sproc.pid) p.send_signal(sig) exit_sig = p.wait() self.assertFalse(psutil.pid_exists(p.pid)) if POSIX: self.assertEqual(exit_sig, -sig) # sproc = get_test_subprocess() p = psutil.Process(sproc.pid) p.send_signal(sig) with mock.patch('psutil.os.kill', side_effect=OSError(errno.ESRCH, "")): with self.assertRaises(psutil.NoSuchProcess): p.send_signal(sig) # sproc = get_test_subprocess() p = psutil.Process(sproc.pid) p.send_signal(sig) with mock.patch('psutil.os.kill', side_effect=OSError(errno.EPERM, "")): with self.assertRaises(psutil.AccessDenied): psutil.Process().send_signal(sig) # Sending a signal to process with PID 0 is not allowed as # it would affect every process in the process group of # the calling process (os.getpid()) instead of PID 0"). if 0 in psutil.pids(): p = psutil.Process(0) self.assertRaises(ValueError, p.send_signal, signal.SIGTERM) def test_wait(self): # check exit code signal sproc = get_test_subprocess() p = psutil.Process(sproc.pid) p.kill() code = p.wait() if POSIX: self.assertEqual(code, -signal.SIGKILL) else: self.assertEqual(code, signal.SIGTERM) self.assertFalse(p.is_running()) sproc = get_test_subprocess() p = psutil.Process(sproc.pid) p.terminate() code = p.wait() if POSIX: self.assertEqual(code, -signal.SIGTERM) else: self.assertEqual(code, signal.SIGTERM) self.assertFalse(p.is_running()) # check sys.exit() code code = "import time, sys; time.sleep(0.01); sys.exit(5);" sproc = get_test_subprocess([PYTHON_EXE, "-c", code]) p = psutil.Process(sproc.pid) self.assertEqual(p.wait(), 5) self.assertFalse(p.is_running()) # Test wait() issued twice. # It is not supposed to raise NSP when the process is gone. # On UNIX this should return None, on Windows it should keep # returning the exit code. sproc = get_test_subprocess([PYTHON_EXE, "-c", code]) p = psutil.Process(sproc.pid) self.assertEqual(p.wait(), 5) self.assertIn(p.wait(), (5, None)) # test timeout sproc = get_test_subprocess() p = psutil.Process(sproc.pid) p.name() self.assertRaises(psutil.TimeoutExpired, p.wait, 0.01) # timeout < 0 not allowed self.assertRaises(ValueError, p.wait, -1) def test_wait_non_children(self): # Test wait() against a process which is not our direct # child. p1, p2 = create_proc_children_pair() self.assertRaises(psutil.TimeoutExpired, p1.wait, 0.01) self.assertRaises(psutil.TimeoutExpired, p2.wait, 0.01) # We also terminate the direct child otherwise the # grandchild will hang until the parent is gone. p1.terminate() p2.terminate() ret1 = p1.wait() ret2 = p2.wait() if POSIX: self.assertEqual(ret1, -signal.SIGTERM) # For processes which are not our children we're supposed # to get None. self.assertEqual(ret2, None) else: self.assertEqual(ret1, signal.SIGTERM) self.assertEqual(ret1, signal.SIGTERM) def test_wait_timeout_0(self): sproc = get_test_subprocess() p = psutil.Process(sproc.pid) self.assertRaises(psutil.TimeoutExpired, p.wait, 0) p.kill() stop_at = time.time() + 2 while True: try: code = p.wait(0) except psutil.TimeoutExpired: if time.time() >= stop_at: raise else: break if POSIX: self.assertEqual(code, -signal.SIGKILL) else: self.assertEqual(code, signal.SIGTERM) self.assertFalse(p.is_running()) def test_cpu_percent(self): p = psutil.Process() p.cpu_percent(interval=0.001) p.cpu_percent(interval=0.001) for x in range(100): percent = p.cpu_percent(interval=None) self.assertIsInstance(percent, float) self.assertGreaterEqual(percent, 0.0) if not POSIX: self.assertLessEqual(percent, 100.0) else: self.assertGreaterEqual(percent, 0.0) with self.assertRaises(ValueError): p.cpu_percent(interval=-1) def test_cpu_percent_numcpus_none(self): # See: https://github.com/giampaolo/psutil/issues/1087 with mock.patch('psutil.cpu_count', return_value=None) as m: psutil.Process().cpu_percent() assert m.called def test_cpu_times(self): times = psutil.Process().cpu_times() assert (times.user > 0.0) or (times.system > 0.0), times assert (times.children_user >= 0.0), times assert (times.children_system >= 0.0), times # make sure returned values can be pretty printed with strftime for name in times._fields: time.strftime("%H:%M:%S", time.localtime(getattr(times, name))) def test_cpu_times_2(self): user_time, kernel_time = psutil.Process().cpu_times()[:2] utime, ktime = os.times()[:2] # Use os.times()[:2] as base values to compare our results # using a tolerance of +/- 0.1 seconds. # It will fail if the difference between the values is > 0.1s. if (max([user_time, utime]) - min([user_time, utime])) > 0.1: self.fail("expected: %s, found: %s" % (utime, user_time)) if (max([kernel_time, ktime]) - min([kernel_time, ktime])) > 0.1: self.fail("expected: %s, found: %s" % (ktime, kernel_time)) @unittest.skipIf(not HAS_PROC_CPU_NUM, "not supported") def test_cpu_num(self): p = psutil.Process() num = p.cpu_num() self.assertGreaterEqual(num, 0) if psutil.cpu_count() == 1: self.assertEqual(num, 0) self.assertIn(p.cpu_num(), range(psutil.cpu_count())) def test_create_time(self): sproc = get_test_subprocess() now = time.time() p = psutil.Process(sproc.pid) create_time = p.create_time() # Use time.time() as base value to compare our result using a # tolerance of +/- 1 second. # It will fail if the difference between the values is > 2s. difference = abs(create_time - now) if difference > 2: self.fail("expected: %s, found: %s, difference: %s" % (now, create_time, difference)) # make sure returned value can be pretty printed with strftime time.strftime("%Y %m %d %H:%M:%S", time.localtime(p.create_time())) @unittest.skipIf(not POSIX, 'POSIX only') @unittest.skipIf(TRAVIS, 'not reliable on TRAVIS') def test_terminal(self): terminal = psutil.Process().terminal() if sys.stdin.isatty() or sys.stdout.isatty(): tty = os.path.realpath(sh('tty')) self.assertEqual(terminal, tty) else: self.assertIsNone(terminal) @unittest.skipIf(not HAS_PROC_IO_COUNTERS, 'not supported') @skip_on_not_implemented(only_if=LINUX) def test_io_counters(self): p = psutil.Process() # test reads io1 = p.io_counters() with open(PYTHON_EXE, 'rb') as f: f.read() io2 = p.io_counters() if not BSD and not AIX: self.assertGreater(io2.read_count, io1.read_count) self.assertEqual(io2.write_count, io1.write_count) if LINUX: self.assertGreater(io2.read_chars, io1.read_chars) self.assertEqual(io2.write_chars, io1.write_chars) else: self.assertGreaterEqual(io2.read_bytes, io1.read_bytes) self.assertGreaterEqual(io2.write_bytes, io1.write_bytes) # test writes io1 = p.io_counters() with tempfile.TemporaryFile(prefix=TESTFILE_PREFIX) as f: if PY3: f.write(bytes("x" * 1000000, 'ascii')) else: f.write("x" * 1000000) io2 = p.io_counters() self.assertGreaterEqual(io2.write_count, io1.write_count) self.assertGreaterEqual(io2.write_bytes, io1.write_bytes) self.assertGreaterEqual(io2.read_count, io1.read_count) self.assertGreaterEqual(io2.read_bytes, io1.read_bytes) if LINUX: self.assertGreater(io2.write_chars, io1.write_chars) self.assertGreaterEqual(io2.read_chars, io1.read_chars) # sanity check for i in range(len(io2)): if BSD and i >= 2: # On BSD read_bytes and write_bytes are always set to -1. continue self.assertGreaterEqual(io2[i], 0) self.assertGreaterEqual(io2[i], 0) @unittest.skipIf(not HAS_IONICE, "not supported") @unittest.skipIf(WINDOWS and get_winver() < WIN_VISTA, 'not supported') def test_ionice(self): if LINUX: from psutil import (IOPRIO_CLASS_NONE, IOPRIO_CLASS_RT, IOPRIO_CLASS_BE, IOPRIO_CLASS_IDLE) self.assertEqual(IOPRIO_CLASS_NONE, 0) self.assertEqual(IOPRIO_CLASS_RT, 1) self.assertEqual(IOPRIO_CLASS_BE, 2) self.assertEqual(IOPRIO_CLASS_IDLE, 3) p = psutil.Process() try: p.ionice(2) ioclass, value = p.ionice() if enum is not None: self.assertIsInstance(ioclass, enum.IntEnum) self.assertEqual(ioclass, 2) self.assertEqual(value, 4) # p.ionice(3) ioclass, value = p.ionice() self.assertEqual(ioclass, 3) self.assertEqual(value, 0) # p.ionice(2, 0) ioclass, value = p.ionice() self.assertEqual(ioclass, 2) self.assertEqual(value, 0) p.ionice(2, 7) ioclass, value = p.ionice() self.assertEqual(ioclass, 2) self.assertEqual(value, 7) finally: p.ionice(IOPRIO_CLASS_NONE) else: p = psutil.Process() original = p.ionice() self.assertIsInstance(original, int) try: value = 0 # very low if original == value: value = 1 # low p.ionice(value) self.assertEqual(p.ionice(), value) finally: p.ionice(original) @unittest.skipIf(not HAS_IONICE, "not supported") @unittest.skipIf(WINDOWS and get_winver() < WIN_VISTA, 'not supported') def test_ionice_errs(self): sproc = get_test_subprocess() p = psutil.Process(sproc.pid) if LINUX: self.assertRaises(ValueError, p.ionice, 2, 10) self.assertRaises(ValueError, p.ionice, 2, -1) self.assertRaises(ValueError, p.ionice, 4) self.assertRaises(TypeError, p.ionice, 2, "foo") self.assertRaisesRegex( ValueError, "can't specify value with IOPRIO_CLASS_NONE", p.ionice, psutil.IOPRIO_CLASS_NONE, 1) self.assertRaisesRegex( ValueError, "can't specify value with IOPRIO_CLASS_IDLE", p.ionice, psutil.IOPRIO_CLASS_IDLE, 1) self.assertRaisesRegex( ValueError, "'ioclass' argument must be specified", p.ionice, value=1) else: self.assertRaises(ValueError, p.ionice, 3) self.assertRaises(TypeError, p.ionice, 2, 1) @unittest.skipIf(not HAS_RLIMIT, "not supported") def test_rlimit_get(self): import resource p = psutil.Process(os.getpid()) names = [x for x in dir(psutil) if x.startswith('RLIMIT')] assert names, names for name in names: value = getattr(psutil, name) self.assertGreaterEqual(value, 0) if name in dir(resource): self.assertEqual(value, getattr(resource, name)) # XXX - On PyPy RLIMIT_INFINITY returned by # resource.getrlimit() is reported as a very big long # number instead of -1. It looks like a bug with PyPy. if PYPY: continue self.assertEqual(p.rlimit(value), resource.getrlimit(value)) else: ret = p.rlimit(value) self.assertEqual(len(ret), 2) self.assertGreaterEqual(ret[0], -1) self.assertGreaterEqual(ret[1], -1) @unittest.skipIf(not HAS_RLIMIT, "not supported") def test_rlimit_set(self): sproc = get_test_subprocess() p = psutil.Process(sproc.pid) p.rlimit(psutil.RLIMIT_NOFILE, (5, 5)) self.assertEqual(p.rlimit(psutil.RLIMIT_NOFILE), (5, 5)) # If pid is 0 prlimit() applies to the calling process and # we don't want that. with self.assertRaises(ValueError): psutil._psplatform.Process(0).rlimit(0) with self.assertRaises(ValueError): p.rlimit(psutil.RLIMIT_NOFILE, (5, 5, 5)) @unittest.skipIf(not HAS_RLIMIT, "not supported") def test_rlimit(self): p = psutil.Process() soft, hard = p.rlimit(psutil.RLIMIT_FSIZE) try: p.rlimit(psutil.RLIMIT_FSIZE, (1024, hard)) with open(TESTFN, "wb") as f: f.write(b"X" * 1024) # write() or flush() doesn't always cause the exception # but close() will. with self.assertRaises(IOError) as exc: with open(TESTFN, "wb") as f: f.write(b"X" * 1025) self.assertEqual(exc.exception.errno if PY3 else exc.exception[0], errno.EFBIG) finally: p.rlimit(psutil.RLIMIT_FSIZE, (soft, hard)) self.assertEqual(p.rlimit(psutil.RLIMIT_FSIZE), (soft, hard)) @unittest.skipIf(not HAS_RLIMIT, "not supported") def test_rlimit_infinity(self): # First set a limit, then re-set it by specifying INFINITY # and assume we overridden the previous limit. p = psutil.Process() soft, hard = p.rlimit(psutil.RLIMIT_FSIZE) try: p.rlimit(psutil.RLIMIT_FSIZE, (1024, hard)) p.rlimit(psutil.RLIMIT_FSIZE, (psutil.RLIM_INFINITY, hard)) with open(TESTFN, "wb") as f: f.write(b"X" * 2048) finally: p.rlimit(psutil.RLIMIT_FSIZE, (soft, hard)) self.assertEqual(p.rlimit(psutil.RLIMIT_FSIZE), (soft, hard)) @unittest.skipIf(not HAS_RLIMIT, "not supported") def test_rlimit_infinity_value(self): # RLIMIT_FSIZE should be RLIM_INFINITY, which will be a really # big number on a platform with large file support. On these # platforms we need to test that the get/setrlimit functions # properly convert the number to a C long long and that the # conversion doesn't raise an error. p = psutil.Process() soft, hard = p.rlimit(psutil.RLIMIT_FSIZE) self.assertEqual(psutil.RLIM_INFINITY, hard) p.rlimit(psutil.RLIMIT_FSIZE, (soft, hard)) def test_num_threads(self): # on certain platforms such as Linux we might test for exact # thread number, since we always have with 1 thread per process, # but this does not apply across all platforms (OSX, Windows) p = psutil.Process() if OPENBSD: try: step1 = p.num_threads() except psutil.AccessDenied: raise unittest.SkipTest("on OpenBSD this requires root access") else: step1 = p.num_threads() with ThreadTask(): step2 = p.num_threads() self.assertEqual(step2, step1 + 1) @unittest.skipIf(not WINDOWS, 'WINDOWS only') def test_num_handles(self): # a better test is done later into test/_windows.py p = psutil.Process() self.assertGreater(p.num_handles(), 0) @unittest.skipIf(not HAS_THREADS, 'not supported') def test_threads(self): p = psutil.Process() if OPENBSD: try: step1 = p.threads() except psutil.AccessDenied: raise unittest.SkipTest("on OpenBSD this requires root access") else: step1 = p.threads() with ThreadTask(): step2 = p.threads() self.assertEqual(len(step2), len(step1) + 1) # on Linux, first thread id is supposed to be this process if LINUX: self.assertEqual(step2[0].id, os.getpid()) athread = step2[0] # test named tuple self.assertEqual(athread.id, athread[0]) self.assertEqual(athread.user_time, athread[1]) self.assertEqual(athread.system_time, athread[2]) @retry_before_failing() @skip_on_access_denied(only_if=OSX) @unittest.skipIf(not HAS_THREADS, 'not supported') def test_threads_2(self): sproc = get_test_subprocess() p = psutil.Process(sproc.pid) if OPENBSD: try: p.threads() except psutil.AccessDenied: raise unittest.SkipTest( "on OpenBSD this requires root access") self.assertAlmostEqual( p.cpu_times().user, sum([x.user_time for x in p.threads()]), delta=0.1) self.assertAlmostEqual( p.cpu_times().system, sum([x.system_time for x in p.threads()]), delta=0.1) def test_memory_info(self): p = psutil.Process() # step 1 - get a base value to compare our results rss1, vms1 = p.memory_info()[:2] percent1 = p.memory_percent() self.assertGreater(rss1, 0) self.assertGreater(vms1, 0) # step 2 - allocate some memory memarr = [None] * 1500000 rss2, vms2 = p.memory_info()[:2] percent2 = p.memory_percent() # step 3 - make sure that the memory usage bumped up self.assertGreater(rss2, rss1) self.assertGreaterEqual(vms2, vms1) # vms might be equal self.assertGreater(percent2, percent1) del memarr if WINDOWS: mem = p.memory_info() self.assertEqual(mem.rss, mem.wset) self.assertEqual(mem.vms, mem.pagefile) mem = p.memory_info() for name in mem._fields: self.assertGreaterEqual(getattr(mem, name), 0) def test_memory_full_info(self): total = psutil.virtual_memory().total mem = psutil.Process().memory_full_info() for name in mem._fields: value = getattr(mem, name) self.assertGreaterEqual(value, 0, msg=(name, value)) self.assertLessEqual(value, total, msg=(name, value, total)) if LINUX or WINDOWS or OSX: self.assertGreaterEqual(mem.uss, 0) if LINUX: self.assertGreaterEqual(mem.pss, 0) self.assertGreaterEqual(mem.swap, 0) @unittest.skipIf(not HAS_MEMORY_MAPS, "not supported") def test_memory_maps(self): p = psutil.Process() maps = p.memory_maps() paths = [x for x in maps] self.assertEqual(len(paths), len(set(paths))) ext_maps = p.memory_maps(grouped=False) for nt in maps: if not nt.path.startswith('['): assert os.path.isabs(nt.path), nt.path if POSIX: try: assert os.path.exists(nt.path) or \ os.path.islink(nt.path), nt.path except AssertionError: if not LINUX: raise else: # https://github.com/giampaolo/psutil/issues/759 with open('/proc/self/smaps') as f: data = f.read() if "%s (deleted)" % nt.path not in data: raise else: # XXX - On Windows we have this strange behavior with # 64 bit dlls: they are visible via explorer but cannot # be accessed via os.stat() (wtf?). if '64' not in os.path.basename(nt.path): assert os.path.exists(nt.path), nt.path for nt in ext_maps: for fname in nt._fields: value = getattr(nt, fname) if fname == 'path': continue elif fname in ('addr', 'perms'): assert value, value else: self.assertIsInstance(value, (int, long)) assert value >= 0, value @unittest.skipIf(not HAS_MEMORY_MAPS, "not supported") def test_memory_maps_lists_lib(self): # Make sure a newly loaded shared lib is listed. with copyload_shared_lib() as path: def normpath(p): return os.path.realpath(os.path.normcase(p)) libpaths = [normpath(x.path) for x in psutil.Process().memory_maps()] self.assertIn(normpath(path), libpaths) def test_memory_percent(self): p = psutil.Process() ret = p.memory_percent() assert 0 <= ret <= 100, ret ret = p.memory_percent(memtype='vms') assert 0 <= ret <= 100, ret assert 0 <= ret <= 100, ret self.assertRaises(ValueError, p.memory_percent, memtype="?!?") if LINUX or OSX or WINDOWS: ret = p.memory_percent(memtype='uss') assert 0 <= ret <= 100, ret assert 0 <= ret <= 100, ret def test_is_running(self): sproc = get_test_subprocess() p = psutil.Process(sproc.pid) assert p.is_running() assert p.is_running() p.kill() p.wait() assert not p.is_running() assert not p.is_running() def test_exe(self): sproc = get_test_subprocess() exe = psutil.Process(sproc.pid).exe() try: self.assertEqual(exe, PYTHON_EXE) except AssertionError: if WINDOWS and len(exe) == len(PYTHON_EXE): # on Windows we don't care about case sensitivity normcase = os.path.normcase self.assertEqual(normcase(exe), normcase(PYTHON_EXE)) else: # certain platforms such as BSD are more accurate returning: # "/usr/local/bin/python2.7" # ...instead of: # "/usr/local/bin/python" # We do not want to consider this difference in accuracy # an error. ver = "%s.%s" % (sys.version_info[0], sys.version_info[1]) try: self.assertEqual(exe.replace(ver, ''), PYTHON_EXE.replace(ver, '')) except AssertionError: # Tipically OSX. Really not sure what to do here. pass out = sh([exe, "-c", "import os; print('hey')"]) self.assertEqual(out, 'hey') def test_cmdline(self): cmdline = [PYTHON_EXE, "-c", "import time; time.sleep(60)"] sproc = get_test_subprocess(cmdline) try: self.assertEqual(' '.join(psutil.Process(sproc.pid).cmdline()), ' '.join(cmdline)) except AssertionError: # XXX - most of the times the underlying sysctl() call on Net # and Open BSD returns a truncated string. # Also /proc/pid/cmdline behaves the same so it looks # like this is a kernel bug. # XXX - AIX truncates long arguments in /proc/pid/cmdline if NETBSD or OPENBSD or AIX: self.assertEqual( psutil.Process(sproc.pid).cmdline()[0], PYTHON_EXE) else: raise def test_name(self): sproc = get_test_subprocess(PYTHON_EXE) name = psutil.Process(sproc.pid).name().lower() pyexe = os.path.basename(os.path.realpath(sys.executable)).lower() assert pyexe.startswith(name), (pyexe, name) # XXX @unittest.skipIf(SUNOS, "broken on SUNOS") @unittest.skipIf(AIX, "broken on AIX") def test_prog_w_funky_name(self): # Test that name(), exe() and cmdline() correctly handle programs # with funky chars such as spaces and ")", see: # https://github.com/giampaolo/psutil/issues/628 def rm(): # Try to limit occasional failures on Appveyor: # https://ci.appveyor.com/project/giampaolo/psutil/build/1350/ # job/lbo3bkju55le850n try: safe_rmpath(funky_path) except OSError: pass funky_path = TESTFN + 'foo bar )' create_exe(funky_path) self.addCleanup(rm) cmdline = [funky_path, "-c", "import time; [time.sleep(0.01) for x in range(3000)];" "arg1", "arg2", "", "arg3", ""] sproc = get_test_subprocess(cmdline) p = psutil.Process(sproc.pid) # ...in order to try to prevent occasional failures on travis if TRAVIS: wait_for_pid(p.pid) self.assertEqual(p.cmdline(), cmdline) self.assertEqual(p.name(), os.path.basename(funky_path)) self.assertEqual(os.path.normcase(p.exe()), os.path.normcase(funky_path)) @unittest.skipIf(not POSIX, 'POSIX only') def test_uids(self): p = psutil.Process() real, effective, saved = p.uids() # os.getuid() refers to "real" uid self.assertEqual(real, os.getuid()) # os.geteuid() refers to "effective" uid self.assertEqual(effective, os.geteuid()) # No such thing as os.getsuid() ("saved" uid), but starting # from python 2.7 we have os.getresuid() which returns all # of them. if hasattr(os, "getresuid"): self.assertEqual(os.getresuid(), p.uids()) @unittest.skipIf(not POSIX, 'POSIX only') def test_gids(self): p = psutil.Process() real, effective, saved = p.gids() # os.getuid() refers to "real" uid self.assertEqual(real, os.getgid()) # os.geteuid() refers to "effective" uid self.assertEqual(effective, os.getegid()) # No such thing as os.getsgid() ("saved" gid), but starting # from python 2.7 we have os.getresgid() which returns all # of them. if hasattr(os, "getresuid"): self.assertEqual(os.getresgid(), p.gids()) def test_nice(self): p = psutil.Process() self.assertRaises(TypeError, p.nice, "str") if WINDOWS: try: init = p.nice() if sys.version_info > (3, 4): self.assertIsInstance(init, enum.IntEnum) else: self.assertIsInstance(init, int) self.assertEqual(init, psutil.NORMAL_PRIORITY_CLASS) p.nice(psutil.HIGH_PRIORITY_CLASS) self.assertEqual(p.nice(), psutil.HIGH_PRIORITY_CLASS) p.nice(psutil.NORMAL_PRIORITY_CLASS) self.assertEqual(p.nice(), psutil.NORMAL_PRIORITY_CLASS) finally: p.nice(psutil.NORMAL_PRIORITY_CLASS) else: first_nice = p.nice() try: if hasattr(os, "getpriority"): self.assertEqual( os.getpriority(os.PRIO_PROCESS, os.getpid()), p.nice()) p.nice(1) self.assertEqual(p.nice(), 1) if hasattr(os, "getpriority"): self.assertEqual( os.getpriority(os.PRIO_PROCESS, os.getpid()), p.nice()) # XXX - going back to previous nice value raises # AccessDenied on OSX if not OSX: p.nice(0) self.assertEqual(p.nice(), 0) except psutil.AccessDenied: pass finally: try: p.nice(first_nice) except psutil.AccessDenied: pass def test_status(self): p = psutil.Process() self.assertEqual(p.status(), psutil.STATUS_RUNNING) def test_username(self): sproc = get_test_subprocess() p = psutil.Process(sproc.pid) username = p.username() if WINDOWS: domain, username = username.split('\\') self.assertEqual(username, getpass.getuser()) if 'USERDOMAIN' in os.environ: self.assertEqual(domain, os.environ['USERDOMAIN']) else: self.assertEqual(username, getpass.getuser()) def test_cwd(self): sproc = get_test_subprocess() p = psutil.Process(sproc.pid) self.assertEqual(p.cwd(), os.getcwd()) def test_cwd_2(self): cmd = [PYTHON_EXE, "-c", "import os, time; os.chdir('..'); time.sleep(60)"] sproc = get_test_subprocess(cmd) p = psutil.Process(sproc.pid) call_until(p.cwd, "ret == os.path.dirname(os.getcwd())") @unittest.skipIf(not HAS_CPU_AFFINITY, 'not supported') def test_cpu_affinity(self): p = psutil.Process() initial = p.cpu_affinity() assert initial, initial self.addCleanup(p.cpu_affinity, initial) if hasattr(os, "sched_getaffinity"): self.assertEqual(initial, list(os.sched_getaffinity(p.pid))) self.assertEqual(len(initial), len(set(initial))) all_cpus = list(range(len(psutil.cpu_percent(percpu=True)))) # Work around travis failure: # https://travis-ci.org/giampaolo/psutil/builds/284173194 for n in all_cpus if not TRAVIS else initial: p.cpu_affinity([n]) self.assertEqual(p.cpu_affinity(), [n]) if hasattr(os, "sched_getaffinity"): self.assertEqual(p.cpu_affinity(), list(os.sched_getaffinity(p.pid))) # also test num_cpu() if hasattr(p, "num_cpu"): self.assertEqual(p.cpu_affinity()[0], p.num_cpu()) # [] is an alias for "all eligible CPUs"; on Linux this may # not be equal to all available CPUs, see: # https://github.com/giampaolo/psutil/issues/956 p.cpu_affinity([]) if LINUX: self.assertEqual(p.cpu_affinity(), p._proc._get_eligible_cpus()) else: self.assertEqual(p.cpu_affinity(), all_cpus) if hasattr(os, "sched_getaffinity"): self.assertEqual(p.cpu_affinity(), list(os.sched_getaffinity(p.pid))) # self.assertRaises(TypeError, p.cpu_affinity, 1) p.cpu_affinity(initial) # it should work with all iterables, not only lists p.cpu_affinity(set(all_cpus)) p.cpu_affinity(tuple(all_cpus)) @unittest.skipIf(not HAS_CPU_AFFINITY, 'not supported') def test_cpu_affinity_errs(self): sproc = get_test_subprocess() p = psutil.Process(sproc.pid) invalid_cpu = [len(psutil.cpu_times(percpu=True)) + 10] self.assertRaises(ValueError, p.cpu_affinity, invalid_cpu) self.assertRaises(ValueError, p.cpu_affinity, range(10000, 11000)) self.assertRaises(TypeError, p.cpu_affinity, [0, "1"]) self.assertRaises(ValueError, p.cpu_affinity, [0, -1]) @unittest.skipIf(not HAS_CPU_AFFINITY, 'not supported') def test_cpu_affinity_all_combinations(self): p = psutil.Process() initial = p.cpu_affinity() assert initial, initial self.addCleanup(p.cpu_affinity, initial) # All possible CPU set combinations. combos = [] for l in range(0, len(initial) + 1): for subset in itertools.combinations(initial, l): if subset: combos.append(list(subset)) for combo in combos: p.cpu_affinity(combo) self.assertEqual(p.cpu_affinity(), combo) # TODO: #595 @unittest.skipIf(BSD, "broken on BSD") # can't find any process file on Appveyor @unittest.skipIf(APPVEYOR, "unreliable on APPVEYOR") def test_open_files(self): # current process p = psutil.Process() files = p.open_files() self.assertFalse(TESTFN in files) with open(TESTFN, 'wb') as f: f.write(b'x' * 1024) f.flush() # give the kernel some time to see the new file files = call_until(p.open_files, "len(ret) != %i" % len(files)) for file in files: if file.path == TESTFN: if LINUX: self.assertEqual(file.position, 1024) break else: self.fail("no file found; files=%s" % repr(files)) for file in files: assert os.path.isfile(file.path), file # another process cmdline = "import time; f = open(r'%s', 'r'); time.sleep(60);" % TESTFN sproc = get_test_subprocess([PYTHON_EXE, "-c", cmdline]) p = psutil.Process(sproc.pid) for x in range(100): filenames = [x.path for x in p.open_files()] if TESTFN in filenames: break time.sleep(.01) else: self.assertIn(TESTFN, filenames) for file in filenames: assert os.path.isfile(file), file # TODO: #595 @unittest.skipIf(BSD, "broken on BSD") # can't find any process file on Appveyor @unittest.skipIf(APPVEYOR, "unreliable on APPVEYOR") def test_open_files_2(self): # test fd and path fields with open(TESTFN, 'w') as fileobj: p = psutil.Process() for file in p.open_files(): if file.path == fileobj.name or file.fd == fileobj.fileno(): break else: self.fail("no file found; files=%s" % repr(p.open_files())) self.assertEqual(file.path, fileobj.name) if WINDOWS: self.assertEqual(file.fd, -1) else: self.assertEqual(file.fd, fileobj.fileno()) # test positions ntuple = p.open_files()[0] self.assertEqual(ntuple[0], ntuple.path) self.assertEqual(ntuple[1], ntuple.fd) # test file is gone self.assertNotIn(fileobj.name, p.open_files()) @unittest.skipIf(not POSIX, 'POSIX only') def test_num_fds(self): p = psutil.Process() start = p.num_fds() file = open(TESTFN, 'w') self.addCleanup(file.close) self.assertEqual(p.num_fds(), start + 1) sock = socket.socket() self.addCleanup(sock.close) self.assertEqual(p.num_fds(), start + 2) file.close() sock.close() self.assertEqual(p.num_fds(), start) @skip_on_not_implemented(only_if=LINUX) @unittest.skipIf(OPENBSD or NETBSD, "not reliable on OPENBSD & NETBSD") def test_num_ctx_switches(self): p = psutil.Process() before = sum(p.num_ctx_switches()) for x in range(500000): after = sum(p.num_ctx_switches()) if after > before: return self.fail("num ctx switches still the same after 50.000 iterations") def test_ppid(self): if hasattr(os, 'getppid'): self.assertEqual(psutil.Process().ppid(), os.getppid()) this_parent = os.getpid() sproc = get_test_subprocess() p = psutil.Process(sproc.pid) self.assertEqual(p.ppid(), this_parent) # no other process is supposed to have us as parent reap_children(recursive=True) if APPVEYOR: # Occasional failures, see: # https://ci.appveyor.com/project/giampaolo/psutil/build/ # job/0hs623nenj7w4m33 return for p in psutil.process_iter(): if p.pid == sproc.pid: continue # XXX: sometimes this fails on Windows; not sure why. self.assertNotEqual(p.ppid(), this_parent, msg=p) def test_parent(self): this_parent = os.getpid() sproc = get_test_subprocess() p = psutil.Process(sproc.pid) self.assertEqual(p.parent().pid, this_parent) def test_parent_disappeared(self): # Emulate a case where the parent process disappeared. sproc = get_test_subprocess() p = psutil.Process(sproc.pid) with mock.patch("psutil.Process", side_effect=psutil.NoSuchProcess(0, 'foo')): self.assertIsNone(p.parent()) def test_children(self): p = psutil.Process() self.assertEqual(p.children(), []) self.assertEqual(p.children(recursive=True), []) # On Windows we set the flag to 0 in order to cancel out the # CREATE_NO_WINDOW flag (enabled by default) which creates # an extra "conhost.exe" child. sproc = get_test_subprocess(creationflags=0) children1 = p.children() children2 = p.children(recursive=True) for children in (children1, children2): self.assertEqual(len(children), 1) self.assertEqual(children[0].pid, sproc.pid) self.assertEqual(children[0].ppid(), os.getpid()) def test_children_recursive(self): # Test children() against two sub processes, p1 and p2, where # p1 (our child) spawned p2 (our grandchild). p1, p2 = create_proc_children_pair() p = psutil.Process() self.assertEqual(p.children(), [p1]) self.assertEqual(p.children(recursive=True), [p1, p2]) # If the intermediate process is gone there's no way for # children() to recursively find it. p1.terminate() p1.wait() self.assertEqual(p.children(recursive=True), []) def test_children_duplicates(self): # find the process which has the highest number of children table = collections.defaultdict(int) for p in psutil.process_iter(): try: table[p.ppid()] += 1 except psutil.Error: pass # this is the one, now let's make sure there are no duplicates pid = sorted(table.items(), key=lambda x: x[1])[-1][0] p = psutil.Process(pid) try: c = p.children(recursive=True) except psutil.AccessDenied: # windows pass else: self.assertEqual(len(c), len(set(c))) def test_suspend_resume(self): sproc = get_test_subprocess() p = psutil.Process(sproc.pid) p.suspend() for x in range(100): if p.status() == psutil.STATUS_STOPPED: break time.sleep(0.01) p.resume() self.assertNotEqual(p.status(), psutil.STATUS_STOPPED) def test_invalid_pid(self): self.assertRaises(TypeError, psutil.Process, "1") self.assertRaises(ValueError, psutil.Process, -1) def test_as_dict(self): p = psutil.Process() d = p.as_dict(attrs=['exe', 'name']) self.assertEqual(sorted(d.keys()), ['exe', 'name']) p = psutil.Process(min(psutil.pids())) d = p.as_dict(attrs=['connections'], ad_value='foo') if not isinstance(d['connections'], list): self.assertEqual(d['connections'], 'foo') # Test ad_value is set on AccessDenied. with mock.patch('psutil.Process.nice', create=True, side_effect=psutil.AccessDenied): self.assertEqual( p.as_dict(attrs=["nice"], ad_value=1), {"nice": 1}) # Test that NoSuchProcess bubbles up. with mock.patch('psutil.Process.nice', create=True, side_effect=psutil.NoSuchProcess(p.pid, "name")): self.assertRaises( psutil.NoSuchProcess, p.as_dict, attrs=["nice"]) # Test that ZombieProcess is swallowed. with mock.patch('psutil.Process.nice', create=True, side_effect=psutil.ZombieProcess(p.pid, "name")): self.assertEqual( p.as_dict(attrs=["nice"], ad_value="foo"), {"nice": "foo"}) # By default APIs raising NotImplementedError are # supposed to be skipped. with mock.patch('psutil.Process.nice', create=True, side_effect=NotImplementedError): d = p.as_dict() self.assertNotIn('nice', list(d.keys())) # ...unless the user explicitly asked for some attr. with self.assertRaises(NotImplementedError): p.as_dict(attrs=["nice"]) # errors with self.assertRaises(TypeError): p.as_dict('name') with self.assertRaises(ValueError): p.as_dict(['foo']) with self.assertRaises(ValueError): p.as_dict(['foo', 'bar']) def test_oneshot(self): with mock.patch("psutil._psplatform.Process.cpu_times") as m: p = psutil.Process() with p.oneshot(): p.cpu_times() p.cpu_times() self.assertEqual(m.call_count, 1) with mock.patch("psutil._psplatform.Process.cpu_times") as m: p.cpu_times() p.cpu_times() self.assertEqual(m.call_count, 2) def test_oneshot_twice(self): # Test the case where the ctx manager is __enter__ed twice. # The second __enter__ is supposed to resut in a NOOP. with mock.patch("psutil._psplatform.Process.cpu_times") as m1: with mock.patch("psutil._psplatform.Process.oneshot_enter") as m2: p = psutil.Process() with p.oneshot(): p.cpu_times() p.cpu_times() with p.oneshot(): p.cpu_times() p.cpu_times() self.assertEqual(m1.call_count, 1) self.assertEqual(m2.call_count, 1) with mock.patch("psutil._psplatform.Process.cpu_times") as m: p.cpu_times() p.cpu_times() self.assertEqual(m.call_count, 2) def test_halfway_terminated_process(self): # Test that NoSuchProcess exception gets raised in case the # process dies after we create the Process object. # Example: # >>> proc = Process(1234) # >>> time.sleep(2) # time-consuming task, process dies in meantime # >>> proc.name() # Refers to Issue #15 sproc = get_test_subprocess() p = psutil.Process(sproc.pid) p.terminate() p.wait() if WINDOWS: call_until(psutil.pids, "%s not in ret" % p.pid) self.assertFalse(p.is_running()) # self.assertFalse(p.pid in psutil.pids(), msg="retcode = %s" % # retcode) excluded_names = ['pid', 'is_running', 'wait', 'create_time', 'oneshot', 'memory_info_ex'] if LINUX and not HAS_RLIMIT: excluded_names.append('rlimit') for name in dir(p): if (name.startswith('_') or name in excluded_names): continue try: meth = getattr(p, name) # get/set methods if name == 'nice': if POSIX: ret = meth(1) else: ret = meth(psutil.NORMAL_PRIORITY_CLASS) elif name == 'ionice': ret = meth() ret = meth(2) elif name == 'rlimit': ret = meth(psutil.RLIMIT_NOFILE) ret = meth(psutil.RLIMIT_NOFILE, (5, 5)) elif name == 'cpu_affinity': ret = meth() ret = meth([0]) elif name == 'send_signal': ret = meth(signal.SIGTERM) else: ret = meth() except psutil.ZombieProcess: self.fail("ZombieProcess for %r was not supposed to happen" % name) except psutil.NoSuchProcess: pass except psutil.AccessDenied: if OPENBSD and name in ('threads', 'num_threads'): pass else: raise except NotImplementedError: pass else: self.fail( "NoSuchProcess exception not raised for %r, retval=%s" % ( name, ret)) @unittest.skipIf(not POSIX, 'POSIX only') def test_zombie_process(self): def succeed_or_zombie_p_exc(fun, *args, **kwargs): try: return fun(*args, **kwargs) except (psutil.ZombieProcess, psutil.AccessDenied): pass zpid = create_zombie_proc() self.addCleanup(reap_children, recursive=True) # A zombie process should always be instantiable zproc = psutil.Process(zpid) # ...and at least its status always be querable self.assertEqual(zproc.status(), psutil.STATUS_ZOMBIE) # ...and it should be considered 'running' self.assertTrue(zproc.is_running()) # ...and as_dict() shouldn't crash zproc.as_dict() # if cmdline succeeds it should be an empty list ret = succeed_or_zombie_p_exc(zproc.suspend) if ret is not None: self.assertEqual(ret, []) if hasattr(zproc, "rlimit"): succeed_or_zombie_p_exc(zproc.rlimit, psutil.RLIMIT_NOFILE) succeed_or_zombie_p_exc(zproc.rlimit, psutil.RLIMIT_NOFILE, (5, 5)) # set methods succeed_or_zombie_p_exc(zproc.parent) if hasattr(zproc, 'cpu_affinity'): try: succeed_or_zombie_p_exc(zproc.cpu_affinity, [0]) except ValueError as err: if TRAVIS and LINUX and "not eligible" in str(err): # https://travis-ci.org/giampaolo/psutil/jobs/279890461 pass else: raise succeed_or_zombie_p_exc(zproc.nice, 0) if hasattr(zproc, 'ionice'): if LINUX: succeed_or_zombie_p_exc(zproc.ionice, 2, 0) else: succeed_or_zombie_p_exc(zproc.ionice, 0) # Windows if hasattr(zproc, 'rlimit'): succeed_or_zombie_p_exc(zproc.rlimit, psutil.RLIMIT_NOFILE, (5, 5)) succeed_or_zombie_p_exc(zproc.suspend) succeed_or_zombie_p_exc(zproc.resume) succeed_or_zombie_p_exc(zproc.terminate) succeed_or_zombie_p_exc(zproc.kill) # ...its parent should 'see' it # edit: not true on BSD and OSX # descendants = [x.pid for x in psutil.Process().children( # recursive=True)] # self.assertIn(zpid, descendants) # XXX should we also assume ppid be usable? Note: this # would be an important use case as the only way to get # rid of a zombie is to kill its parent. # self.assertEqual(zpid.ppid(), os.getpid()) # ...and all other APIs should be able to deal with it self.assertTrue(psutil.pid_exists(zpid)) if not TRAVIS and OSX: # For some reason this started failing all of the sudden. # Maybe they upgraded OSX version? # https://travis-ci.org/giampaolo/psutil/jobs/310896404 self.assertIn(zpid, psutil.pids()) self.assertIn(zpid, [x.pid for x in psutil.process_iter()]) psutil._pmap = {} self.assertIn(zpid, [x.pid for x in psutil.process_iter()]) @unittest.skipIf(not POSIX, 'POSIX only') def test_zombie_process_is_running_w_exc(self): # Emulate a case where internally is_running() raises # ZombieProcess. p = psutil.Process() with mock.patch("psutil.Process", side_effect=psutil.ZombieProcess(0)) as m: assert p.is_running() assert m.called @unittest.skipIf(not POSIX, 'POSIX only') def test_zombie_process_status_w_exc(self): # Emulate a case where internally status() raises # ZombieProcess. p = psutil.Process() with mock.patch("psutil._psplatform.Process.status", side_effect=psutil.ZombieProcess(0)) as m: self.assertEqual(p.status(), psutil.STATUS_ZOMBIE) assert m.called def test_pid_0(self): # Process(0) is supposed to work on all platforms except Linux if 0 not in psutil.pids(): self.assertRaises(psutil.NoSuchProcess, psutil.Process, 0) return # test all methods p = psutil.Process(0) for name in psutil._as_dict_attrnames: if name == 'pid': continue meth = getattr(p, name) try: ret = meth() except psutil.AccessDenied: pass else: if name in ("uids", "gids"): self.assertEqual(ret.real, 0) elif name == "username": if POSIX: self.assertEqual(p.username(), 'root') elif WINDOWS: self.assertEqual(p.username(), 'NT AUTHORITY\\SYSTEM') elif name == "name": assert name, name if hasattr(p, 'rlimit'): try: p.rlimit(psutil.RLIMIT_FSIZE) except psutil.AccessDenied: pass p.as_dict() if not OPENBSD: self.assertIn(0, psutil.pids()) self.assertTrue(psutil.pid_exists(0)) @unittest.skipIf(not HAS_ENVIRON, "not supported") def test_environ(self): def clean_dict(d): # Most of these are problematic on Travis. d.pop("PSUTIL_TESTING", None) d.pop("PLAT", None) d.pop("HOME", None) if OSX: d.pop("__CF_USER_TEXT_ENCODING", None) d.pop("VERSIONER_PYTHON_PREFER_32_BIT", None) d.pop("VERSIONER_PYTHON_VERSION", None) return dict( [(k.rstrip("\r\n"), v.rstrip("\r\n")) for k, v in d.items()]) self.maxDiff = None p = psutil.Process() d1 = clean_dict(p.environ()) d2 = clean_dict(os.environ.copy()) self.assertEqual(d1, d2) @unittest.skipIf(not HAS_ENVIRON, "not supported") @unittest.skipIf(not POSIX, "POSIX only") def test_weird_environ(self): # environment variables can contain values without an equals sign code = textwrap.dedent(""" #include #include char * const argv[] = {"cat", 0}; char * const envp[] = {"A=1", "X", "C=3", 0}; int main(void) { /* Close stderr on exec so parent can wait for the execve to * finish. */ if (fcntl(2, F_SETFD, FD_CLOEXEC) != 0) return 0; return execve("/bin/cat", argv, envp); } """) path = TESTFN create_exe(path, c_code=code) self.addCleanup(safe_rmpath, path) sproc = get_test_subprocess([path], stdin=subprocess.PIPE, stderr=subprocess.PIPE) p = psutil.Process(sproc.pid) wait_for_pid(p.pid) self.assertTrue(p.is_running()) # Wait for process to exec or exit. self.assertEqual(sproc.stderr.read(), b"") self.assertEqual(p.environ(), {"A": "1", "C": "3"}) sproc.communicate() self.assertEqual(sproc.returncode, 0) # =================================================================== # --- Limited user tests # =================================================================== if POSIX and os.getuid() == 0: class LimitedUserTestCase(TestProcess): """Repeat the previous tests by using a limited user. Executed only on UNIX and only if the user who run the test script is root. """ # the uid/gid the test suite runs under if hasattr(os, 'getuid'): PROCESS_UID = os.getuid() PROCESS_GID = os.getgid() def __init__(self, *args, **kwargs): TestProcess.__init__(self, *args, **kwargs) # re-define all existent test methods in order to # ignore AccessDenied exceptions for attr in [x for x in dir(self) if x.startswith('test')]: meth = getattr(self, attr) def test_(self): try: meth() except psutil.AccessDenied: pass setattr(self, attr, types.MethodType(test_, self)) def setUp(self): safe_rmpath(TESTFN) TestProcess.setUp(self) os.setegid(1000) os.seteuid(1000) def tearDown(self): os.setegid(self.PROCESS_UID) os.seteuid(self.PROCESS_GID) TestProcess.tearDown(self) def test_nice(self): try: psutil.Process().nice(-1) except psutil.AccessDenied: pass else: self.fail("exception not raised") def test_zombie_process(self): # causes problems if test test suite is run as root pass # =================================================================== # --- psutil.Popen tests # =================================================================== class TestPopen(unittest.TestCase): """Tests for psutil.Popen class.""" def tearDown(self): reap_children() def test_misc(self): # XXX this test causes a ResourceWarning on Python 3 because # psutil.__subproc instance doesn't get propertly freed. # Not sure what to do though. cmd = [PYTHON_EXE, "-c", "import time; time.sleep(60);"] with psutil.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as proc: proc.name() proc.cpu_times() proc.stdin self.assertTrue(dir(proc)) self.assertRaises(AttributeError, getattr, proc, 'foo') proc.terminate() def test_ctx_manager(self): with psutil.Popen([PYTHON_EXE, "-V"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) as proc: proc.communicate() assert proc.stdout.closed assert proc.stderr.closed assert proc.stdin.closed self.assertEqual(proc.returncode, 0) def test_kill_terminate(self): # subprocess.Popen()'s terminate(), kill() and send_signal() do # not raise exception after the process is gone. psutil.Popen # diverges from that. cmd = [PYTHON_EXE, "-c", "import time; time.sleep(60);"] with psutil.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as proc: proc.terminate() proc.wait() self.assertRaises(psutil.NoSuchProcess, proc.terminate) self.assertRaises(psutil.NoSuchProcess, proc.kill) self.assertRaises(psutil.NoSuchProcess, proc.send_signal, signal.SIGTERM) if WINDOWS and sys.version_info >= (2, 7): self.assertRaises(psutil.NoSuchProcess, proc.send_signal, signal.CTRL_C_EVENT) self.assertRaises(psutil.NoSuchProcess, proc.send_signal, signal.CTRL_BREAK_EVENT) if __name__ == '__main__': run_test_module_by_name(__file__) PK!=£=G=Gtest_memory_leaks.pynu[ # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Tests for detecting function memory leaks (typically the ones implemented in C). It does so by calling a function many times and checking whether process memory usage keeps increasing between calls or over time. Note that this may produce false positives (especially on Windows for some reason). """ from __future__ import print_function import errno import functools import gc import os import sys import threading import time import psutil import psutil._common from psutil import LINUX from psutil import OPENBSD from psutil import OSX from psutil import POSIX from psutil import SUNOS from psutil import WINDOWS from psutil._compat import xrange from psutil.tests import create_sockets from psutil.tests import get_test_subprocess from psutil.tests import HAS_CPU_AFFINITY from psutil.tests import HAS_CPU_FREQ from psutil.tests import HAS_ENVIRON from psutil.tests import HAS_IONICE from psutil.tests import HAS_MEMORY_MAPS from psutil.tests import HAS_PROC_CPU_NUM from psutil.tests import HAS_PROC_IO_COUNTERS from psutil.tests import HAS_RLIMIT from psutil.tests import HAS_SENSORS_BATTERY from psutil.tests import HAS_SENSORS_FANS from psutil.tests import HAS_SENSORS_TEMPERATURES from psutil.tests import reap_children from psutil.tests import run_test_module_by_name from psutil.tests import safe_rmpath from psutil.tests import skip_on_access_denied from psutil.tests import TESTFN from psutil.tests import TRAVIS from psutil.tests import unittest LOOPS = 1000 MEMORY_TOLERANCE = 4096 RETRY_FOR = 3 SKIP_PYTHON_IMPL = True if TRAVIS else False cext = psutil._psplatform.cext thisproc = psutil.Process() SKIP_PYTHON_IMPL = True if TRAVIS else False # =================================================================== # utils # =================================================================== def skip_if_linux(): return unittest.skipIf(LINUX and SKIP_PYTHON_IMPL, "worthless on LINUX (pure python)") def bytes2human(n): """ http://code.activestate.com/recipes/578019 >>> bytes2human(10000) '9.8K' >>> bytes2human(100001221) '95.4M' """ symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y') prefix = {} for i, s in enumerate(symbols): prefix[s] = 1 << (i + 1) * 10 for s in reversed(symbols): if n >= prefix[s]: value = float(n) / prefix[s] return '%.2f%s' % (value, s) return "%sB" % n class TestMemLeak(unittest.TestCase): """Base framework class which calls a function many times and produces a failure if process memory usage keeps increasing between calls or over time. """ tolerance = MEMORY_TOLERANCE loops = LOOPS retry_for = RETRY_FOR def setUp(self): gc.collect() def execute(self, fun, *args, **kwargs): """Test a callable.""" def call_many_times(): for x in xrange(loops): self._call(fun, *args, **kwargs) del x gc.collect() tolerance = kwargs.pop('tolerance_', None) or self.tolerance loops = kwargs.pop('loops_', None) or self.loops retry_for = kwargs.pop('retry_for_', None) or self.retry_for # warm up for x in range(10): self._call(fun, *args, **kwargs) self.assertEqual(gc.garbage, []) self.assertEqual(threading.active_count(), 1) self.assertEqual(thisproc.children(), []) # Get 2 distinct memory samples, before and after having # called fun repeadetly. # step 1 call_many_times() mem1 = self._get_mem() # step 2 call_many_times() mem2 = self._get_mem() diff1 = mem2 - mem1 if diff1 > tolerance: # This doesn't necessarily mean we have a leak yet. # At this point we assume that after having called the # function so many times the memory usage is stabilized # and if there are no leaks it should not increase # anymore. # Let's keep calling fun for 3 more seconds and fail if # we notice any difference. ncalls = 0 stop_at = time.time() + retry_for while time.time() <= stop_at: self._call(fun, *args, **kwargs) ncalls += 1 del stop_at gc.collect() mem3 = self._get_mem() diff2 = mem3 - mem2 if mem3 > mem2: # failure extra_proc_mem = bytes2human(diff1 + diff2) print("exta proc mem: %s" % extra_proc_mem, file=sys.stderr) msg = "+%s after %s calls, +%s after another %s calls, " msg += "+%s extra proc mem" msg = msg % ( bytes2human(diff1), loops, bytes2human(diff2), ncalls, extra_proc_mem) self.fail(msg) def execute_w_exc(self, exc, fun, *args, **kwargs): """Convenience function which tests a callable raising an exception. """ def call(): self.assertRaises(exc, fun, *args, **kwargs) self.execute(call) @staticmethod def _get_mem(): # By using USS memory it seems it's less likely to bump # into false positives. if LINUX or WINDOWS or OSX: return thisproc.memory_full_info().uss else: return thisproc.memory_info().rss @staticmethod def _call(fun, *args, **kwargs): fun(*args, **kwargs) # =================================================================== # Process class # =================================================================== class TestProcessObjectLeaks(TestMemLeak): """Test leaks of Process class methods.""" proc = thisproc def test_coverage(self): skip = set(( "pid", "as_dict", "children", "cpu_affinity", "cpu_percent", "ionice", "is_running", "kill", "memory_info_ex", "memory_percent", "nice", "oneshot", "parent", "rlimit", "send_signal", "suspend", "terminate", "wait")) for name in dir(psutil.Process): if name.startswith('_'): continue if name in skip: continue self.assertTrue(hasattr(self, "test_" + name), msg=name) @skip_if_linux() def test_name(self): self.execute(self.proc.name) @skip_if_linux() def test_cmdline(self): self.execute(self.proc.cmdline) @skip_if_linux() def test_exe(self): self.execute(self.proc.exe) @skip_if_linux() def test_ppid(self): self.execute(self.proc.ppid) @unittest.skipIf(not POSIX, "POSIX only") @skip_if_linux() def test_uids(self): self.execute(self.proc.uids) @unittest.skipIf(not POSIX, "POSIX only") @skip_if_linux() def test_gids(self): self.execute(self.proc.gids) @skip_if_linux() def test_status(self): self.execute(self.proc.status) def test_nice_get(self): self.execute(self.proc.nice) def test_nice_set(self): niceness = thisproc.nice() self.execute(self.proc.nice, niceness) @unittest.skipIf(not HAS_IONICE, "not supported") def test_ionice_get(self): self.execute(self.proc.ionice) @unittest.skipIf(not HAS_IONICE, "not supported") def test_ionice_set(self): if WINDOWS: value = thisproc.ionice() self.execute(self.proc.ionice, value) else: self.execute(self.proc.ionice, psutil.IOPRIO_CLASS_NONE) fun = functools.partial(cext.proc_ioprio_set, os.getpid(), -1, 0) self.execute_w_exc(OSError, fun) @unittest.skipIf(not HAS_PROC_IO_COUNTERS, "not supported") @skip_if_linux() def test_io_counters(self): self.execute(self.proc.io_counters) @unittest.skipIf(POSIX, "worthless on POSIX") def test_username(self): self.execute(self.proc.username) @skip_if_linux() def test_create_time(self): self.execute(self.proc.create_time) @skip_if_linux() @skip_on_access_denied(only_if=OPENBSD) def test_num_threads(self): self.execute(self.proc.num_threads) @unittest.skipIf(not WINDOWS, "WINDOWS only") def test_num_handles(self): self.execute(self.proc.num_handles) @unittest.skipIf(not POSIX, "POSIX only") @skip_if_linux() def test_num_fds(self): self.execute(self.proc.num_fds) @skip_if_linux() def test_num_ctx_switches(self): self.execute(self.proc.num_ctx_switches) @skip_if_linux() @skip_on_access_denied(only_if=OPENBSD) def test_threads(self): self.execute(self.proc.threads) @skip_if_linux() def test_cpu_times(self): self.execute(self.proc.cpu_times) @skip_if_linux() @unittest.skipIf(not HAS_PROC_CPU_NUM, "not supported") def test_cpu_num(self): self.execute(self.proc.cpu_num) @skip_if_linux() def test_memory_info(self): self.execute(self.proc.memory_info) @skip_if_linux() def test_memory_full_info(self): self.execute(self.proc.memory_full_info) @unittest.skipIf(not POSIX, "POSIX only") @skip_if_linux() def test_terminal(self): self.execute(self.proc.terminal) @unittest.skipIf(POSIX and SKIP_PYTHON_IMPL, "worthless on POSIX (pure python)") def test_resume(self): self.execute(self.proc.resume) @skip_if_linux() def test_cwd(self): self.execute(self.proc.cwd) @unittest.skipIf(not HAS_CPU_AFFINITY, "not supported") def test_cpu_affinity_get(self): self.execute(self.proc.cpu_affinity) @unittest.skipIf(not HAS_CPU_AFFINITY, "not supported") def test_cpu_affinity_set(self): affinity = thisproc.cpu_affinity() self.execute(self.proc.cpu_affinity, affinity) if not TRAVIS: self.execute_w_exc(ValueError, self.proc.cpu_affinity, [-1]) @skip_if_linux() def test_open_files(self): safe_rmpath(TESTFN) # needed after UNIX socket test has run with open(TESTFN, 'w'): self.execute(self.proc.open_files) # OSX implementation is unbelievably slow @unittest.skipIf(OSX, "too slow on OSX") @unittest.skipIf(not HAS_MEMORY_MAPS, "not supported") @skip_if_linux() def test_memory_maps(self): self.execute(self.proc.memory_maps) @unittest.skipIf(not LINUX, "LINUX only") @unittest.skipIf(not HAS_RLIMIT, "not supported") def test_rlimit_get(self): self.execute(self.proc.rlimit, psutil.RLIMIT_NOFILE) @unittest.skipIf(not LINUX, "LINUX only") @unittest.skipIf(not HAS_RLIMIT, "not supported") def test_rlimit_set(self): limit = thisproc.rlimit(psutil.RLIMIT_NOFILE) self.execute(self.proc.rlimit, psutil.RLIMIT_NOFILE, limit) self.execute_w_exc(OSError, self.proc.rlimit, -1) @skip_if_linux() # Windows implementation is based on a single system-wide # function (tested later). @unittest.skipIf(WINDOWS, "worthless on WINDOWS") def test_connections(self): # TODO: UNIX sockets are temporarily implemented by parsing # 'pfiles' cmd output; we don't want that part of the code to # be executed. with create_sockets(): kind = 'inet' if SUNOS else 'all' self.execute(self.proc.connections, kind) @unittest.skipIf(not HAS_ENVIRON, "not supported") def test_environ(self): self.execute(self.proc.environ) @unittest.skipIf(not WINDOWS, "WINDOWS only") def test_proc_info(self): self.execute(cext.proc_info, os.getpid()) class TestTerminatedProcessLeaks(TestProcessObjectLeaks): """Repeat the tests above looking for leaks occurring when dealing with terminated processes raising NoSuchProcess exception. The C functions are still invoked but will follow different code paths. We'll check those code paths. """ @classmethod def setUpClass(cls): super(TestTerminatedProcessLeaks, cls).setUpClass() p = get_test_subprocess() cls.proc = psutil.Process(p.pid) cls.proc.kill() cls.proc.wait() @classmethod def tearDownClass(cls): super(TestTerminatedProcessLeaks, cls).tearDownClass() reap_children() def _call(self, fun, *args, **kwargs): try: fun(*args, **kwargs) except psutil.NoSuchProcess: pass if WINDOWS: def test_kill(self): self.execute(self.proc.kill) def test_terminate(self): self.execute(self.proc.terminate) def test_suspend(self): self.execute(self.proc.suspend) def test_resume(self): self.execute(self.proc.resume) def test_wait(self): self.execute(self.proc.wait) def test_proc_info(self): # test dual implementation def call(): try: return cext.proc_info(self.proc.pid) except OSError as err: if err.errno != errno.ESRCH: raise self.execute(call) # =================================================================== # system APIs # =================================================================== class TestModuleFunctionsLeaks(TestMemLeak): """Test leaks of psutil module functions.""" def test_coverage(self): skip = set(( "version_info", "__version__", "process_iter", "wait_procs", "cpu_percent", "cpu_times_percent", "cpu_count")) for name in psutil.__all__: if not name.islower(): continue if name in skip: continue self.assertTrue(hasattr(self, "test_" + name), msg=name) # --- cpu @skip_if_linux() def test_cpu_count_logical(self): self.execute(psutil.cpu_count, logical=True) @skip_if_linux() def test_cpu_count_physical(self): self.execute(psutil.cpu_count, logical=False) @skip_if_linux() def test_cpu_times(self): self.execute(psutil.cpu_times) @skip_if_linux() def test_per_cpu_times(self): self.execute(psutil.cpu_times, percpu=True) def test_cpu_stats(self): self.execute(psutil.cpu_stats) @skip_if_linux() @unittest.skipIf(not HAS_CPU_FREQ, "not supported") def test_cpu_freq(self): self.execute(psutil.cpu_freq) # --- mem def test_virtual_memory(self): self.execute(psutil.virtual_memory) # TODO: remove this skip when this gets fixed @unittest.skipIf(SUNOS, "worthless on SUNOS (uses a subprocess)") def test_swap_memory(self): self.execute(psutil.swap_memory) @unittest.skipIf(POSIX and SKIP_PYTHON_IMPL, "worthless on POSIX (pure python)") def test_pid_exists(self): self.execute(psutil.pid_exists, os.getpid()) # --- disk @unittest.skipIf(POSIX and SKIP_PYTHON_IMPL, "worthless on POSIX (pure python)") def test_disk_usage(self): self.execute(psutil.disk_usage, '.') def test_disk_partitions(self): self.execute(psutil.disk_partitions) @unittest.skipIf(LINUX and not os.path.exists('/proc/diskstats'), '/proc/diskstats not available on this Linux version') @skip_if_linux() def test_disk_io_counters(self): self.execute(psutil.disk_io_counters, nowrap=False) # --- proc @skip_if_linux() def test_pids(self): self.execute(psutil.pids) # --- net @skip_if_linux() def test_net_io_counters(self): self.execute(psutil.net_io_counters, nowrap=False) @unittest.skipIf(LINUX, "worthless on Linux (pure python)") @unittest.skipIf(OSX and os.getuid() != 0, "need root access") def test_net_connections(self): with create_sockets(): self.execute(psutil.net_connections) def test_net_if_addrs(self): # Note: verified that on Windows this was a false positive. self.execute(psutil.net_if_addrs, tolerance_=80 * 1024 if WINDOWS else None) @unittest.skipIf(TRAVIS, "EPERM on travis") def test_net_if_stats(self): self.execute(psutil.net_if_stats) # --- sensors @skip_if_linux() @unittest.skipIf(not HAS_SENSORS_BATTERY, "not supported") def test_sensors_battery(self): self.execute(psutil.sensors_battery) @skip_if_linux() @unittest.skipIf(not HAS_SENSORS_TEMPERATURES, "not supported") def test_sensors_temperatures(self): self.execute(psutil.sensors_temperatures) @skip_if_linux() @unittest.skipIf(not HAS_SENSORS_FANS, "not supported") def test_sensors_fans(self): self.execute(psutil.sensors_fans) # --- others @skip_if_linux() def test_boot_time(self): self.execute(psutil.boot_time) # XXX - on Windows this produces a false positive @unittest.skipIf(WINDOWS, "XXX produces a false positive on Windows") def test_users(self): self.execute(psutil.users) if WINDOWS: # --- win services def test_win_service_iter(self): self.execute(cext.winservice_enumerate) def test_win_service_get(self): pass def test_win_service_get_config(self): name = next(psutil.win_service_iter()).name() self.execute(cext.winservice_query_config, name) def test_win_service_get_status(self): name = next(psutil.win_service_iter()).name() self.execute(cext.winservice_query_status, name) def test_win_service_get_description(self): name = next(psutil.win_service_iter()).name() self.execute(cext.winservice_query_descr, name) if __name__ == '__main__': run_test_module_by_name(__file__) PK!Ժ/5 test_misc.pynu[# -*- coding: utf-8 -*- # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Miscellaneous tests. """ import ast import collections import contextlib import errno import json import os import pickle import socket import stat from psutil import LINUX from psutil import POSIX from psutil import WINDOWS from psutil._common import memoize from psutil._common import memoize_when_activated from psutil._common import supports_ipv6 from psutil._common import wrap_numbers from psutil._compat import PY3 from psutil.tests import APPVEYOR from psutil.tests import bind_socket from psutil.tests import bind_unix_socket from psutil.tests import call_until from psutil.tests import chdir from psutil.tests import create_proc_children_pair from psutil.tests import create_sockets from psutil.tests import create_zombie_proc from psutil.tests import DEVNULL from psutil.tests import get_free_port from psutil.tests import get_test_subprocess from psutil.tests import HAS_BATTERY from psutil.tests import HAS_CONNECTIONS_UNIX from psutil.tests import HAS_MEMORY_FULL_INFO from psutil.tests import HAS_MEMORY_MAPS from psutil.tests import HAS_SENSORS_BATTERY from psutil.tests import HAS_SENSORS_FANS from psutil.tests import HAS_SENSORS_TEMPERATURES from psutil.tests import import_module_by_path from psutil.tests import is_namedtuple from psutil.tests import mock from psutil.tests import PYTHON_EXE from psutil.tests import reap_children from psutil.tests import reload_module from psutil.tests import retry from psutil.tests import ROOT_DIR from psutil.tests import run_test_module_by_name from psutil.tests import safe_rmpath from psutil.tests import SCRIPTS_DIR from psutil.tests import sh from psutil.tests import tcp_socketpair from psutil.tests import TESTFN from psutil.tests import TOX from psutil.tests import TRAVIS from psutil.tests import unittest from psutil.tests import unix_socket_path from psutil.tests import unix_socketpair from psutil.tests import wait_for_file from psutil.tests import wait_for_pid import psutil import psutil.tests # =================================================================== # --- Misc / generic tests. # =================================================================== class TestMisc(unittest.TestCase): def test_process__repr__(self, func=repr): p = psutil.Process() r = func(p) self.assertIn("psutil.Process", r) self.assertIn("pid=%s" % p.pid, r) self.assertIn("name=", r) self.assertIn(p.name(), r) with mock.patch.object(psutil.Process, "name", side_effect=psutil.ZombieProcess(os.getpid())): p = psutil.Process() r = func(p) self.assertIn("pid=%s" % p.pid, r) self.assertIn("zombie", r) self.assertNotIn("name=", r) with mock.patch.object(psutil.Process, "name", side_effect=psutil.NoSuchProcess(os.getpid())): p = psutil.Process() r = func(p) self.assertIn("pid=%s" % p.pid, r) self.assertIn("terminated", r) self.assertNotIn("name=", r) with mock.patch.object(psutil.Process, "name", side_effect=psutil.AccessDenied(os.getpid())): p = psutil.Process() r = func(p) self.assertIn("pid=%s" % p.pid, r) self.assertNotIn("name=", r) def test_process__str__(self): self.test_process__repr__(func=str) def test_no_such_process__repr__(self, func=repr): self.assertEqual( repr(psutil.NoSuchProcess(321)), "psutil.NoSuchProcess process no longer exists (pid=321)") self.assertEqual( repr(psutil.NoSuchProcess(321, name='foo')), "psutil.NoSuchProcess process no longer exists (pid=321, " "name='foo')") self.assertEqual( repr(psutil.NoSuchProcess(321, msg='foo')), "psutil.NoSuchProcess foo") def test_zombie_process__repr__(self, func=repr): self.assertEqual( repr(psutil.ZombieProcess(321)), "psutil.ZombieProcess process still exists but it's a zombie " "(pid=321)") self.assertEqual( repr(psutil.ZombieProcess(321, name='foo')), "psutil.ZombieProcess process still exists but it's a zombie " "(pid=321, name='foo')") self.assertEqual( repr(psutil.ZombieProcess(321, name='foo', ppid=1)), "psutil.ZombieProcess process still exists but it's a zombie " "(pid=321, name='foo', ppid=1)") self.assertEqual( repr(psutil.ZombieProcess(321, msg='foo')), "psutil.ZombieProcess foo") def test_access_denied__repr__(self, func=repr): self.assertEqual( repr(psutil.AccessDenied(321)), "psutil.AccessDenied (pid=321)") self.assertEqual( repr(psutil.AccessDenied(321, name='foo')), "psutil.AccessDenied (pid=321, name='foo')") self.assertEqual( repr(psutil.AccessDenied(321, msg='foo')), "psutil.AccessDenied foo") def test_timeout_expired__repr__(self, func=repr): self.assertEqual( repr(psutil.TimeoutExpired(321)), "psutil.TimeoutExpired timeout after 321 seconds") self.assertEqual( repr(psutil.TimeoutExpired(321, pid=111)), "psutil.TimeoutExpired timeout after 321 seconds (pid=111)") self.assertEqual( repr(psutil.TimeoutExpired(321, pid=111, name='foo')), "psutil.TimeoutExpired timeout after 321 seconds " "(pid=111, name='foo')") def test_process__eq__(self): p1 = psutil.Process() p2 = psutil.Process() self.assertEqual(p1, p2) p2._ident = (0, 0) self.assertNotEqual(p1, p2) self.assertNotEqual(p1, 'foo') def test_process__hash__(self): s = set([psutil.Process(), psutil.Process()]) self.assertEqual(len(s), 1) def test__all__(self): dir_psutil = dir(psutil) for name in dir_psutil: if name in ('callable', 'error', 'namedtuple', 'tests', 'long', 'test', 'NUM_CPUS', 'BOOT_TIME', 'TOTAL_PHYMEM'): continue if not name.startswith('_'): try: __import__(name) except ImportError: if name not in psutil.__all__: fun = getattr(psutil, name) if fun is None: continue if (fun.__doc__ is not None and 'deprecated' not in fun.__doc__.lower()): self.fail('%r not in psutil.__all__' % name) # Import 'star' will break if __all__ is inconsistent, see: # https://github.com/giampaolo/psutil/issues/656 # Can't do `from psutil import *` as it won't work on python 3 # so we simply iterate over __all__. for name in psutil.__all__: self.assertIn(name, dir_psutil) def test_version(self): self.assertEqual('.'.join([str(x) for x in psutil.version_info]), psutil.__version__) def test_process_as_dict_no_new_names(self): # See https://github.com/giampaolo/psutil/issues/813 p = psutil.Process() p.foo = '1' self.assertNotIn('foo', p.as_dict()) def test_memoize(self): @memoize def foo(*args, **kwargs): "foo docstring" calls.append(None) return (args, kwargs) calls = [] # no args for x in range(2): ret = foo() expected = ((), {}) self.assertEqual(ret, expected) self.assertEqual(len(calls), 1) # with args for x in range(2): ret = foo(1) expected = ((1, ), {}) self.assertEqual(ret, expected) self.assertEqual(len(calls), 2) # with args + kwargs for x in range(2): ret = foo(1, bar=2) expected = ((1, ), {'bar': 2}) self.assertEqual(ret, expected) self.assertEqual(len(calls), 3) # clear cache foo.cache_clear() ret = foo() expected = ((), {}) self.assertEqual(ret, expected) self.assertEqual(len(calls), 4) # docstring self.assertEqual(foo.__doc__, "foo docstring") def test_memoize_when_activated(self): class Foo: @memoize_when_activated def foo(self): calls.append(None) f = Foo() calls = [] f.foo() f.foo() self.assertEqual(len(calls), 2) # activate calls = [] f.foo.cache_activate() f.foo() f.foo() self.assertEqual(len(calls), 1) # deactivate calls = [] f.foo.cache_deactivate() f.foo() f.foo() self.assertEqual(len(calls), 2) def test_parse_environ_block(self): from psutil._common import parse_environ_block def k(s): return s.upper() if WINDOWS else s self.assertEqual(parse_environ_block("a=1\0"), {k("a"): "1"}) self.assertEqual(parse_environ_block("a=1\0b=2\0\0"), {k("a"): "1", k("b"): "2"}) self.assertEqual(parse_environ_block("a=1\0b=\0\0"), {k("a"): "1", k("b"): ""}) # ignore everything after \0\0 self.assertEqual(parse_environ_block("a=1\0b=2\0\0c=3\0"), {k("a"): "1", k("b"): "2"}) # ignore everything that is not an assignment self.assertEqual(parse_environ_block("xxx\0a=1\0"), {k("a"): "1"}) self.assertEqual(parse_environ_block("a=1\0=b=2\0"), {k("a"): "1"}) # do not fail if the block is incomplete self.assertEqual(parse_environ_block("a=1\0b=2"), {k("a"): "1"}) def test_supports_ipv6(self): self.addCleanup(supports_ipv6.cache_clear) if supports_ipv6(): with mock.patch('psutil._common.socket') as s: s.has_ipv6 = False supports_ipv6.cache_clear() assert not supports_ipv6() supports_ipv6.cache_clear() with mock.patch('psutil._common.socket.socket', side_effect=socket.error) as s: assert not supports_ipv6() assert s.called supports_ipv6.cache_clear() with mock.patch('psutil._common.socket.socket', side_effect=socket.gaierror) as s: assert not supports_ipv6() supports_ipv6.cache_clear() assert s.called supports_ipv6.cache_clear() with mock.patch('psutil._common.socket.socket.bind', side_effect=socket.gaierror) as s: assert not supports_ipv6() supports_ipv6.cache_clear() assert s.called else: with self.assertRaises(Exception): sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) sock.bind(("::1", 0)) def test_isfile_strict(self): from psutil._common import isfile_strict this_file = os.path.abspath(__file__) assert isfile_strict(this_file) assert not isfile_strict(os.path.dirname(this_file)) with mock.patch('psutil._common.os.stat', side_effect=OSError(errno.EPERM, "foo")): self.assertRaises(OSError, isfile_strict, this_file) with mock.patch('psutil._common.os.stat', side_effect=OSError(errno.EACCES, "foo")): self.assertRaises(OSError, isfile_strict, this_file) with mock.patch('psutil._common.os.stat', side_effect=OSError(errno.EINVAL, "foo")): assert not isfile_strict(this_file) with mock.patch('psutil._common.stat.S_ISREG', return_value=False): assert not isfile_strict(this_file) def test_serialization(self): def check(ret): if json is not None: json.loads(json.dumps(ret)) a = pickle.dumps(ret) b = pickle.loads(a) self.assertEqual(ret, b) check(psutil.Process().as_dict()) check(psutil.virtual_memory()) check(psutil.swap_memory()) check(psutil.cpu_times()) check(psutil.cpu_times_percent(interval=0)) check(psutil.net_io_counters()) if LINUX and not os.path.exists('/proc/diskstats'): pass else: if not APPVEYOR: check(psutil.disk_io_counters()) check(psutil.disk_partitions()) check(psutil.disk_usage(os.getcwd())) check(psutil.users()) def test_setup_script(self): setup_py = os.path.join(ROOT_DIR, 'setup.py') if TRAVIS and not os.path.exists(setup_py): return self.skipTest("can't find setup.py") module = import_module_by_path(setup_py) self.assertRaises(SystemExit, module.setup) self.assertEqual(module.get_version(), psutil.__version__) def test_ad_on_process_creation(self): # We are supposed to be able to instantiate Process also in case # of zombie processes or access denied. with mock.patch.object(psutil.Process, 'create_time', side_effect=psutil.AccessDenied) as meth: psutil.Process() assert meth.called with mock.patch.object(psutil.Process, 'create_time', side_effect=psutil.ZombieProcess(1)) as meth: psutil.Process() assert meth.called with mock.patch.object(psutil.Process, 'create_time', side_effect=ValueError) as meth: with self.assertRaises(ValueError): psutil.Process() assert meth.called def test_sanity_version_check(self): # see: https://github.com/giampaolo/psutil/issues/564 with mock.patch( "psutil._psplatform.cext.version", return_value="0.0.0"): with self.assertRaises(ImportError) as cm: reload_module(psutil) self.assertIn("version conflict", str(cm.exception).lower()) # =================================================================== # --- Tests for wrap_numbers() function. # =================================================================== nt = collections.namedtuple('foo', 'a b c') class TestWrapNumbers(unittest.TestCase): def setUp(self): wrap_numbers.cache_clear() tearDown = setUp def test_first_call(self): input = {'disk1': nt(5, 5, 5)} self.assertEqual(wrap_numbers(input, 'disk_io'), input) def test_input_hasnt_changed(self): input = {'disk1': nt(5, 5, 5)} self.assertEqual(wrap_numbers(input, 'disk_io'), input) self.assertEqual(wrap_numbers(input, 'disk_io'), input) def test_increase_but_no_wrap(self): input = {'disk1': nt(5, 5, 5)} self.assertEqual(wrap_numbers(input, 'disk_io'), input) input = {'disk1': nt(10, 15, 20)} self.assertEqual(wrap_numbers(input, 'disk_io'), input) input = {'disk1': nt(20, 25, 30)} self.assertEqual(wrap_numbers(input, 'disk_io'), input) input = {'disk1': nt(20, 25, 30)} self.assertEqual(wrap_numbers(input, 'disk_io'), input) def test_wrap(self): # let's say 100 is the threshold input = {'disk1': nt(100, 100, 100)} self.assertEqual(wrap_numbers(input, 'disk_io'), input) # first wrap restarts from 10 input = {'disk1': nt(100, 100, 10)} self.assertEqual(wrap_numbers(input, 'disk_io'), {'disk1': nt(100, 100, 110)}) # then it remains the same input = {'disk1': nt(100, 100, 10)} self.assertEqual(wrap_numbers(input, 'disk_io'), {'disk1': nt(100, 100, 110)}) # then it goes up input = {'disk1': nt(100, 100, 90)} self.assertEqual(wrap_numbers(input, 'disk_io'), {'disk1': nt(100, 100, 190)}) # then it wraps again input = {'disk1': nt(100, 100, 20)} self.assertEqual(wrap_numbers(input, 'disk_io'), {'disk1': nt(100, 100, 210)}) # and remains the same input = {'disk1': nt(100, 100, 20)} self.assertEqual(wrap_numbers(input, 'disk_io'), {'disk1': nt(100, 100, 210)}) # now wrap another num input = {'disk1': nt(50, 100, 20)} self.assertEqual(wrap_numbers(input, 'disk_io'), {'disk1': nt(150, 100, 210)}) # and again input = {'disk1': nt(40, 100, 20)} self.assertEqual(wrap_numbers(input, 'disk_io'), {'disk1': nt(190, 100, 210)}) # keep it the same input = {'disk1': nt(40, 100, 20)} self.assertEqual(wrap_numbers(input, 'disk_io'), {'disk1': nt(190, 100, 210)}) def test_changing_keys(self): # Emulate a case where the second call to disk_io() # (or whatever) provides a new disk, then the new disk # disappears on the third call. input = {'disk1': nt(5, 5, 5)} self.assertEqual(wrap_numbers(input, 'disk_io'), input) input = {'disk1': nt(5, 5, 5), 'disk2': nt(7, 7, 7)} self.assertEqual(wrap_numbers(input, 'disk_io'), input) input = {'disk1': nt(8, 8, 8)} self.assertEqual(wrap_numbers(input, 'disk_io'), input) def test_changing_keys_w_wrap(self): input = {'disk1': nt(50, 50, 50), 'disk2': nt(100, 100, 100)} self.assertEqual(wrap_numbers(input, 'disk_io'), input) # disk 2 wraps input = {'disk1': nt(50, 50, 50), 'disk2': nt(100, 100, 10)} self.assertEqual(wrap_numbers(input, 'disk_io'), {'disk1': nt(50, 50, 50), 'disk2': nt(100, 100, 110)}) # disk 2 disappears input = {'disk1': nt(50, 50, 50)} self.assertEqual(wrap_numbers(input, 'disk_io'), input) # then it appears again; the old wrap is supposed to be # gone. input = {'disk1': nt(50, 50, 50), 'disk2': nt(100, 100, 100)} self.assertEqual(wrap_numbers(input, 'disk_io'), input) # remains the same input = {'disk1': nt(50, 50, 50), 'disk2': nt(100, 100, 100)} self.assertEqual(wrap_numbers(input, 'disk_io'), input) # and then wraps again input = {'disk1': nt(50, 50, 50), 'disk2': nt(100, 100, 10)} self.assertEqual(wrap_numbers(input, 'disk_io'), {'disk1': nt(50, 50, 50), 'disk2': nt(100, 100, 110)}) def test_real_data(self): d = {'nvme0n1': (300, 508, 640, 1571, 5970, 1987, 2049, 451751, 47048), 'nvme0n1p1': (1171, 2, 5600256, 1024, 516, 0, 0, 0, 8), 'nvme0n1p2': (54, 54, 2396160, 5165056, 4, 24, 30, 1207, 28), 'nvme0n1p3': (2389, 4539, 5154, 150, 4828, 1844, 2019, 398, 348)} self.assertEqual(wrap_numbers(d, 'disk_io'), d) self.assertEqual(wrap_numbers(d, 'disk_io'), d) # decrease this ↓ d = {'nvme0n1': (100, 508, 640, 1571, 5970, 1987, 2049, 451751, 47048), 'nvme0n1p1': (1171, 2, 5600256, 1024, 516, 0, 0, 0, 8), 'nvme0n1p2': (54, 54, 2396160, 5165056, 4, 24, 30, 1207, 28), 'nvme0n1p3': (2389, 4539, 5154, 150, 4828, 1844, 2019, 398, 348)} out = wrap_numbers(d, 'disk_io') self.assertEqual(out['nvme0n1'][0], 400) # --- cache tests def test_cache_first_call(self): input = {'disk1': nt(5, 5, 5)} wrap_numbers(input, 'disk_io') cache = wrap_numbers.cache_info() self.assertEqual(cache[0], {'disk_io': input}) self.assertEqual(cache[1], {'disk_io': {}}) self.assertEqual(cache[2], {'disk_io': {}}) def test_cache_call_twice(self): input = {'disk1': nt(5, 5, 5)} wrap_numbers(input, 'disk_io') input = {'disk1': nt(10, 10, 10)} wrap_numbers(input, 'disk_io') cache = wrap_numbers.cache_info() self.assertEqual(cache[0], {'disk_io': input}) self.assertEqual( cache[1], {'disk_io': {('disk1', 0): 0, ('disk1', 1): 0, ('disk1', 2): 0}}) self.assertEqual(cache[2], {'disk_io': {}}) def test_cache_wrap(self): # let's say 100 is the threshold input = {'disk1': nt(100, 100, 100)} wrap_numbers(input, 'disk_io') # first wrap restarts from 10 input = {'disk1': nt(100, 100, 10)} wrap_numbers(input, 'disk_io') cache = wrap_numbers.cache_info() self.assertEqual(cache[0], {'disk_io': input}) self.assertEqual( cache[1], {'disk_io': {('disk1', 0): 0, ('disk1', 1): 0, ('disk1', 2): 100}}) self.assertEqual(cache[2], {'disk_io': {'disk1': set([('disk1', 2)])}}) def assert_(): cache = wrap_numbers.cache_info() self.assertEqual( cache[1], {'disk_io': {('disk1', 0): 0, ('disk1', 1): 0, ('disk1', 2): 100}}) self.assertEqual(cache[2], {'disk_io': {'disk1': set([('disk1', 2)])}}) # then it remains the same input = {'disk1': nt(100, 100, 10)} wrap_numbers(input, 'disk_io') cache = wrap_numbers.cache_info() self.assertEqual(cache[0], {'disk_io': input}) assert_() # then it goes up input = {'disk1': nt(100, 100, 90)} wrap_numbers(input, 'disk_io') cache = wrap_numbers.cache_info() self.assertEqual(cache[0], {'disk_io': input}) assert_() # then it wraps again input = {'disk1': nt(100, 100, 20)} wrap_numbers(input, 'disk_io') cache = wrap_numbers.cache_info() self.assertEqual(cache[0], {'disk_io': input}) self.assertEqual( cache[1], {'disk_io': {('disk1', 0): 0, ('disk1', 1): 0, ('disk1', 2): 190}}) self.assertEqual(cache[2], {'disk_io': {'disk1': set([('disk1', 2)])}}) def test_cache_changing_keys(self): input = {'disk1': nt(5, 5, 5)} wrap_numbers(input, 'disk_io') input = {'disk1': nt(5, 5, 5), 'disk2': nt(7, 7, 7)} wrap_numbers(input, 'disk_io') cache = wrap_numbers.cache_info() self.assertEqual(cache[0], {'disk_io': input}) self.assertEqual( cache[1], {'disk_io': {('disk1', 0): 0, ('disk1', 1): 0, ('disk1', 2): 0}}) self.assertEqual(cache[2], {'disk_io': {}}) def test_cache_clear(self): input = {'disk1': nt(5, 5, 5)} wrap_numbers(input, 'disk_io') wrap_numbers(input, 'disk_io') wrap_numbers.cache_clear('disk_io') self.assertEqual(wrap_numbers.cache_info(), ({}, {}, {})) wrap_numbers.cache_clear('disk_io') wrap_numbers.cache_clear('?!?') @unittest.skipIf( not psutil.disk_io_counters() or not psutil.net_io_counters(), "no disks or NICs available") def test_cache_clear_public_apis(self): psutil.disk_io_counters() psutil.net_io_counters() caches = wrap_numbers.cache_info() for cache in caches: self.assertIn('psutil.disk_io_counters', cache) self.assertIn('psutil.net_io_counters', cache) psutil.disk_io_counters.cache_clear() caches = wrap_numbers.cache_info() for cache in caches: self.assertIn('psutil.net_io_counters', cache) self.assertNotIn('psutil.disk_io_counters', cache) psutil.net_io_counters.cache_clear() caches = wrap_numbers.cache_info() self.assertEqual(caches, ({}, {}, {})) # =================================================================== # --- Example script tests # =================================================================== @unittest.skipIf(TOX, "can't test on TOX") # See: https://travis-ci.org/giampaolo/psutil/jobs/295224806 @unittest.skipIf(TRAVIS and not os.path.exists(SCRIPTS_DIR), "can't locate scripts directory") class TestScripts(unittest.TestCase): """Tests for scripts in the "scripts" directory.""" @staticmethod def assert_stdout(exe, *args, **kwargs): exe = '%s' % os.path.join(SCRIPTS_DIR, exe) cmd = [PYTHON_EXE, exe] for arg in args: cmd.append(arg) try: out = sh(cmd, **kwargs).strip() except RuntimeError as err: if 'AccessDenied' in str(err): return str(err) else: raise assert out, out return out @staticmethod def assert_syntax(exe, args=None): exe = os.path.join(SCRIPTS_DIR, exe) if PY3: f = open(exe, 'rt', encoding='utf8') else: f = open(exe, 'rt') with f: src = f.read() ast.parse(src) def test_coverage(self): # make sure all example scripts have a test method defined meths = dir(self) for name in os.listdir(SCRIPTS_DIR): if name.endswith('.py'): if 'test_' + os.path.splitext(name)[0] not in meths: # self.assert_stdout(name) self.fail('no test defined for %r script' % os.path.join(SCRIPTS_DIR, name)) @unittest.skipIf(not POSIX, "POSIX only") def test_executable(self): for name in os.listdir(SCRIPTS_DIR): if name.endswith('.py'): path = os.path.join(SCRIPTS_DIR, name) if not stat.S_IXUSR & os.stat(path)[stat.ST_MODE]: self.fail('%r is not executable' % path) def test_disk_usage(self): self.assert_stdout('disk_usage.py') def test_free(self): self.assert_stdout('free.py') def test_meminfo(self): self.assert_stdout('meminfo.py') def test_procinfo(self): self.assert_stdout('procinfo.py', str(os.getpid())) # can't find users on APPVEYOR or TRAVIS @unittest.skipIf(APPVEYOR or TRAVIS and not psutil.users(), "unreliable on APPVEYOR or TRAVIS") def test_who(self): self.assert_stdout('who.py') def test_ps(self): self.assert_stdout('ps.py') def test_pstree(self): self.assert_stdout('pstree.py') def test_netstat(self): self.assert_stdout('netstat.py') # permission denied on travis @unittest.skipIf(TRAVIS, "unreliable on TRAVIS") def test_ifconfig(self): self.assert_stdout('ifconfig.py') @unittest.skipIf(not HAS_MEMORY_MAPS, "not supported") def test_pmap(self): self.assert_stdout('pmap.py', str(os.getpid())) @unittest.skipIf(not HAS_MEMORY_FULL_INFO, "not supported") def test_procsmem(self): self.assert_stdout('procsmem.py', stderr=DEVNULL) def test_killall(self): self.assert_syntax('killall.py') def test_nettop(self): self.assert_syntax('nettop.py') def test_top(self): self.assert_syntax('top.py') def test_iotop(self): self.assert_syntax('iotop.py') def test_pidof(self): output = self.assert_stdout('pidof.py', psutil.Process().name()) self.assertIn(str(os.getpid()), output) @unittest.skipIf(not WINDOWS, "WINDOWS only") def test_winservices(self): self.assert_stdout('winservices.py') def test_cpu_distribution(self): self.assert_syntax('cpu_distribution.py') @unittest.skipIf(not HAS_SENSORS_TEMPERATURES, "not supported") @unittest.skipIf(TRAVIS, "unreliable on TRAVIS") def test_temperatures(self): self.assert_stdout('temperatures.py') @unittest.skipIf(not HAS_SENSORS_FANS, "not supported") @unittest.skipIf(TRAVIS, "unreliable on TRAVIS") def test_fans(self): self.assert_stdout('fans.py') @unittest.skipIf(not HAS_SENSORS_BATTERY, "not supported") @unittest.skipIf(not HAS_BATTERY, "no battery") def test_battery(self): self.assert_stdout('battery.py') def test_sensors(self): self.assert_stdout('sensors.py') # =================================================================== # --- Unit tests for test utilities. # =================================================================== class TestRetryDecorator(unittest.TestCase): @mock.patch('time.sleep') def test_retry_success(self, sleep): # Fail 3 times out of 5; make sure the decorated fun returns. @retry(retries=5, interval=1, logfun=None) def foo(): while queue: queue.pop() 1 / 0 return 1 queue = list(range(3)) self.assertEqual(foo(), 1) self.assertEqual(sleep.call_count, 3) @mock.patch('time.sleep') def test_retry_failure(self, sleep): # Fail 6 times out of 5; th function is supposed to raise exc. @retry(retries=5, interval=1, logfun=None) def foo(): while queue: queue.pop() 1 / 0 return 1 queue = list(range(6)) self.assertRaises(ZeroDivisionError, foo) self.assertEqual(sleep.call_count, 5) @mock.patch('time.sleep') def test_exception_arg(self, sleep): @retry(exception=ValueError, interval=1) def foo(): raise TypeError self.assertRaises(TypeError, foo) self.assertEqual(sleep.call_count, 0) @mock.patch('time.sleep') def test_no_interval_arg(self, sleep): # if interval is not specified sleep is not supposed to be called @retry(retries=5, interval=None, logfun=None) def foo(): 1 / 0 self.assertRaises(ZeroDivisionError, foo) self.assertEqual(sleep.call_count, 0) @mock.patch('time.sleep') def test_retries_arg(self, sleep): @retry(retries=5, interval=1, logfun=None) def foo(): 1 / 0 self.assertRaises(ZeroDivisionError, foo) self.assertEqual(sleep.call_count, 5) @mock.patch('time.sleep') def test_retries_and_timeout_args(self, sleep): self.assertRaises(ValueError, retry, retries=5, timeout=1) class TestSyncTestUtils(unittest.TestCase): def tearDown(self): safe_rmpath(TESTFN) def test_wait_for_pid(self): wait_for_pid(os.getpid()) nopid = max(psutil.pids()) + 99999 with mock.patch('psutil.tests.retry.__iter__', return_value=iter([0])): self.assertRaises(psutil.NoSuchProcess, wait_for_pid, nopid) def test_wait_for_file(self): with open(TESTFN, 'w') as f: f.write('foo') wait_for_file(TESTFN) assert not os.path.exists(TESTFN) def test_wait_for_file_empty(self): with open(TESTFN, 'w'): pass wait_for_file(TESTFN, empty=True) assert not os.path.exists(TESTFN) def test_wait_for_file_no_file(self): with mock.patch('psutil.tests.retry.__iter__', return_value=iter([0])): self.assertRaises(IOError, wait_for_file, TESTFN) def test_wait_for_file_no_delete(self): with open(TESTFN, 'w') as f: f.write('foo') wait_for_file(TESTFN, delete=False) assert os.path.exists(TESTFN) def test_call_until(self): ret = call_until(lambda: 1, "ret == 1") self.assertEqual(ret, 1) class TestFSTestUtils(unittest.TestCase): def setUp(self): safe_rmpath(TESTFN) tearDown = setUp def test_safe_rmpath(self): # test file is removed open(TESTFN, 'w').close() safe_rmpath(TESTFN) assert not os.path.exists(TESTFN) # test no exception if path does not exist safe_rmpath(TESTFN) # test dir is removed os.mkdir(TESTFN) safe_rmpath(TESTFN) assert not os.path.exists(TESTFN) # test other exceptions are raised with mock.patch('psutil.tests.os.stat', side_effect=OSError(errno.EINVAL, "")) as m: with self.assertRaises(OSError): safe_rmpath(TESTFN) assert m.called def test_chdir(self): base = os.getcwd() os.mkdir(TESTFN) with chdir(TESTFN): self.assertEqual(os.getcwd(), os.path.join(base, TESTFN)) self.assertEqual(os.getcwd(), base) class TestProcessUtils(unittest.TestCase): def test_reap_children(self): subp = get_test_subprocess() p = psutil.Process(subp.pid) assert p.is_running() reap_children() assert not p.is_running() assert not psutil.tests._pids_started assert not psutil.tests._subprocesses_started def test_create_proc_children_pair(self): p1, p2 = create_proc_children_pair() self.assertNotEqual(p1.pid, p2.pid) assert p1.is_running() assert p2.is_running() children = psutil.Process().children(recursive=True) self.assertEqual(len(children), 2) self.assertIn(p1, children) self.assertIn(p2, children) self.assertEqual(p1.ppid(), os.getpid()) self.assertEqual(p2.ppid(), p1.pid) # make sure both of them are cleaned up reap_children() assert not p1.is_running() assert not p2.is_running() assert not psutil.tests._pids_started assert not psutil.tests._subprocesses_started @unittest.skipIf(not POSIX, "POSIX only") def test_create_zombie_proc(self): zpid = create_zombie_proc() self.addCleanup(reap_children, recursive=True) p = psutil.Process(zpid) self.assertEqual(p.status(), psutil.STATUS_ZOMBIE) class TestNetUtils(unittest.TestCase): def bind_socket(self): port = get_free_port() with contextlib.closing(bind_socket(addr=('', port))) as s: self.assertEqual(s.getsockname()[1], port) @unittest.skipIf(not POSIX, "POSIX only") def test_bind_unix_socket(self): with unix_socket_path() as name: sock = bind_unix_socket(name) with contextlib.closing(sock): self.assertEqual(sock.family, socket.AF_UNIX) self.assertEqual(sock.type, socket.SOCK_STREAM) self.assertEqual(sock.getsockname(), name) assert os.path.exists(name) assert stat.S_ISSOCK(os.stat(name).st_mode) # UDP with unix_socket_path() as name: sock = bind_unix_socket(name, type=socket.SOCK_DGRAM) with contextlib.closing(sock): self.assertEqual(sock.type, socket.SOCK_DGRAM) def tcp_tcp_socketpair(self): addr = ("127.0.0.1", get_free_port()) server, client = tcp_socketpair(socket.AF_INET, addr=addr) with contextlib.closing(server): with contextlib.closing(client): # Ensure they are connected and the positions are # correct. self.assertEqual(server.getsockname(), addr) self.assertEqual(client.getpeername(), addr) self.assertNotEqual(client.getsockname(), addr) @unittest.skipIf(not POSIX, "POSIX only") def test_unix_socketpair(self): p = psutil.Process() num_fds = p.num_fds() assert not p.connections(kind='unix') with unix_socket_path() as name: server, client = unix_socketpair(name) try: assert os.path.exists(name) assert stat.S_ISSOCK(os.stat(name).st_mode) self.assertEqual(p.num_fds() - num_fds, 2) self.assertEqual(len(p.connections(kind='unix')), 2) self.assertEqual(server.getsockname(), name) self.assertEqual(client.getpeername(), name) finally: client.close() server.close() def test_create_sockets(self): with create_sockets() as socks: fams = collections.defaultdict(int) types = collections.defaultdict(int) for s in socks: fams[s.family] += 1 # work around http://bugs.python.org/issue30204 types[s.getsockopt(socket.SOL_SOCKET, socket.SO_TYPE)] += 1 self.assertGreaterEqual(fams[socket.AF_INET], 2) if supports_ipv6(): self.assertGreaterEqual(fams[socket.AF_INET6], 2) if POSIX and HAS_CONNECTIONS_UNIX: self.assertGreaterEqual(fams[socket.AF_UNIX], 2) self.assertGreaterEqual(types[socket.SOCK_STREAM], 2) self.assertGreaterEqual(types[socket.SOCK_DGRAM], 2) class TestOtherUtils(unittest.TestCase): def test_is_namedtuple(self): assert is_namedtuple(collections.namedtuple('foo', 'a b c')(1, 2, 3)) assert not is_namedtuple(tuple()) if __name__ == '__main__': run_test_module_by_name(__file__) PK!&OperatingSystemTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Environment; use PHPUnit\Framework\TestCase; /** * @covers \SebastianBergmann\Environment\OperatingSystem */ final class OperatingSystemTest extends TestCase { /** * @var \SebastianBergmann\Environment\OperatingSystem */ private $os; protected function setUp(): void { $this->os = new OperatingSystem; } /** * @requires OS Linux */ public function testFamilyCanBeRetrieved(): void { $this->assertEquals('Linux', $this->os->getFamily()); } /** * @requires OS Darwin */ public function testFamilyReturnsDarwinWhenRunningOnDarwin(): void { $this->assertEquals('Darwin', $this->os->getFamily()); } /** * @requires OS Windows */ public function testGetFamilyReturnsWindowsWhenRunningOnWindows(): void { $this->assertSame('Windows', $this->os->getFamily()); } /** * @requires PHP 7.2.0 */ public function testGetFamilyReturnsPhpOsFamilyWhenRunningOnPhp72AndGreater(): void { $this->assertSame(\PHP_OS_FAMILY, $this->os->getFamily()); } } PK!&ConsoleTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Environment; use PHPUnit\Framework\TestCase; /** * @covers \SebastianBergmann\Environment\Console */ final class ConsoleTest extends TestCase { /** * @var \SebastianBergmann\Environment\Console */ private $console; protected function setUp(): void { $this->console = new Console; } /** * @todo Now that this component is PHP 7-only and uses return type declarations * this test makes even less sense than before */ public function testCanDetectIfStdoutIsInteractiveByDefault(): void { $this->assertIsBool($this->console->isInteractive()); } /** * @todo Now that this component is PHP 7-only and uses return type declarations * this test makes even less sense than before */ public function testCanDetectIfFileDescriptorIsInteractive(): void { $this->assertIsBool($this->console->isInteractive(\STDOUT)); } /** * @todo Now that this component is PHP 7-only and uses return type declarations * this test makes even less sense than before */ public function testCanDetectColorSupport(): void { $this->assertIsBool($this->console->hasColorSupport()); } /** * @todo Now that this component is PHP 7-only and uses return type declarations * this test makes even less sense than before */ public function testCanDetectNumberOfColumns(): void { $this->assertIsInt($this->console->getNumberOfColumns()); } } PK!T~lRuntimeTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Environment; use PHPUnit\Framework\TestCase; /** * @covers \SebastianBergmann\Environment\Runtime */ final class RuntimeTest extends TestCase { /** * @var \SebastianBergmann\Environment\Runtime */ private $env; protected function setUp(): void { $this->env = new Runtime; } /** * @requires extension xdebug */ public function testCanCollectCodeCoverageWhenXdebugExtensionIsEnabled(): void { $this->assertTrue($this->env->canCollectCodeCoverage()); } /** * @requires extension pcov */ public function testCanCollectCodeCoverageWhenPcovExtensionIsEnabled(): void { $this->assertTrue($this->env->canCollectCodeCoverage()); } public function testCanCollectCodeCoverageWhenRunningOnPhpdbg(): void { $this->markTestSkippedWhenNotRunningOnPhpdbg(); $this->assertTrue($this->env->canCollectCodeCoverage()); } public function testBinaryCanBeRetrieved(): void { $this->assertNotEmpty($this->env->getBinary()); } /** * @requires PHP */ public function testIsHhvmReturnsFalseWhenRunningOnPhp(): void { $this->assertFalse($this->env->isHHVM()); } /** * @requires PHP */ public function testIsPhpReturnsTrueWhenRunningOnPhp(): void { $this->markTestSkippedWhenRunningOnPhpdbg(); $this->assertTrue($this->env->isPHP()); } /** * @requires extension pcov */ public function testPCOVCanBeDetected(): void { $this->assertTrue($this->env->hasPCOV()); } public function testPhpdbgCanBeDetected(): void { $this->markTestSkippedWhenNotRunningOnPhpdbg(); $this->assertTrue($this->env->hasPHPDBGCodeCoverage()); } /** * @requires extension xdebug */ public function testXdebugCanBeDetected(): void { $this->markTestSkippedWhenRunningOnPhpdbg(); $this->assertTrue($this->env->hasXdebug()); } public function testNameAndVersionCanBeRetrieved(): void { $this->assertNotEmpty($this->env->getNameWithVersion()); } public function testGetNameReturnsPhpdbgWhenRunningOnPhpdbg(): void { $this->markTestSkippedWhenNotRunningOnPhpdbg(); $this->assertSame('PHPDBG', $this->env->getName()); } /** * @requires PHP */ public function testGetNameReturnsPhpdbgWhenRunningOnPhp(): void { $this->markTestSkippedWhenRunningOnPhpdbg(); $this->assertSame('PHP', $this->env->getName()); } public function testNameAndCodeCoverageDriverCanBeRetrieved(): void { $this->assertNotEmpty($this->env->getNameWithVersionAndCodeCoverageDriver()); } /** * @requires PHP */ public function testGetVersionReturnsPhpVersionWhenRunningPhp(): void { $this->assertSame(\PHP_VERSION, $this->env->getVersion()); } /** * @requires PHP */ public function testGetVendorUrlReturnsPhpDotNetWhenRunningPhp(): void { $this->assertSame('https://secure.php.net/', $this->env->getVendorUrl()); } private function markTestSkippedWhenNotRunningOnPhpdbg(): void { if ($this->isRunningOnPhpdbg()) { return; } $this->markTestSkipped('PHPDBG is required.'); } private function markTestSkippedWhenRunningOnPhpdbg(): void { if (!$this->isRunningOnPhpdbg()) { return; } $this->markTestSkipped('Cannot run on PHPDBG'); } private function isRunningOnPhpdbg(): bool { return \PHP_SAPI === 'phpdbg'; } } PK!HyObjectReflectorTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace SebastianBergmann\ObjectReflector; use PHPUnit\Framework\TestCase; use SebastianBergmann\ObjectReflector\TestFixture\ChildClass; use SebastianBergmann\ObjectReflector\TestFixture\ClassWithIntegerAttributeName; /** * @covers SebastianBergmann\ObjectReflector\ObjectReflector */ class ObjectReflectorTest extends TestCase { /** * @var ObjectReflector */ private $objectReflector; protected function setUp()/*: void */ { $this->objectReflector = new ObjectReflector; } public function testReflectsAttributesOfObject()/*: void */ { $o = new ChildClass; $this->assertEquals( [ 'privateInChild' => 'private', 'protectedInChild' => 'protected', 'publicInChild' => 'public', 'undeclared' => 'undeclared', 'SebastianBergmann\ObjectReflector\TestFixture\ParentClass::privateInParent' => 'private', 'SebastianBergmann\ObjectReflector\TestFixture\ParentClass::protectedInParent' => 'protected', 'SebastianBergmann\ObjectReflector\TestFixture\ParentClass::publicInParent' => 'public', ], $this->objectReflector->getAttributes($o) ); } public function testReflectsAttributeWithIntegerName()/*: void */ { $o = new ClassWithIntegerAttributeName; $this->assertEquals( [ 1 => 2 ], $this->objectReflector->getAttributes($o) ); } public function testRaisesExceptionWhenPassedArgumentIsNotAnObject()/*: void */ { $this->expectException(InvalidArgumentException::class); $this->objectReflector->getAttributes(null); } } PK!_fixture/ParentClass.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace SebastianBergmann\ObjectReflector\TestFixture; class ParentClass { private $privateInParent = 'private'; private $protectedInParent = 'protected'; private $publicInParent = 'public'; } PK!AA_fixture/ChildClass.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace SebastianBergmann\ObjectReflector\TestFixture; class ChildClass extends ParentClass { private $privateInChild = 'private'; private $protectedInChild = 'protected'; private $publicInChild = 'public'; public function __construct() { $this->undeclared = 'undeclared'; } } PK!*_fixture/ClassWithIntegerAttributeName.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace SebastianBergmann\ObjectReflector\TestFixture; class ClassWithIntegerAttributeName { public function __construct() { $i = 1; $this->$i = 2; } } PK!001-getopt.phptnu[--TEST-- Console_Getopt --FILE-- $d) { if ($i++ > 0) { print ", "; } print $d[0] . '=' . $d[1]; } print "\n"; print "params: " . implode(", ", $non_opts) . "\n"; print "\n"; } test("-abc", "abc"); test("-abc foo", "abc"); test("-abc foo", "abc:"); test("-abc foo bar gazonk", "abc"); test("-abc foo bar gazonk", "abc:"); test("-a -b -c", "abc"); test("-a -b -c", "abc:"); test("-abc", "ab:c"); test("-abc foo -bar gazonk", "abc"); ?> --EXPECT-- options: a=, b=, c= params: options: a=, b=, c= params: foo options: a=, b=, c=foo params: options: a=, b=, c= params: foo, bar, gazonk options: a=, b=, c=foo params: bar, gazonk options: a=, b=, c= params: Console_Getopt: option requires an argument --c options: a=, b=c params: options: a=, b=, c= params: foo, -bar, gazonk PK! bug11068.phptnu[--TEST-- Console_Getopt [bug 11068] --SKIPIF-- --FILE-- getMessage()."\n"; echo 'FATAL'; exit; } print_r($ret); ?> --EXPECT-- Array ( [0] => Array ( [0] => Array ( [0] => f [1] => jjohnston@mail.com ) [1] => Array ( [0] => --to [1] => hi ) ) [1] => Array ( [0] => - ) )PK! bug10557.phptnu[--TEST-- Console_Getopt [bug 10557] --SKIPIF-- --FILE-- getMessage()."\n"; echo 'FATAL'; exit; } print_r($ret); ?> --EXPECT-- Console_Getopt: option requires an argument --to FATALPK!|EE bug13140.phptnu[--TEST-- Console_Getopt [bug 13140] --SKIPIF-- --FILE-- getopt2($cg->readPHPArgv(), 't', array('test'), true)); print_r($cg->getopt2($cg->readPHPArgv(), 'bar', array('foo'), true)); ?> --EXPECT-- Array ( [0] => Array ( [0] => Array ( [0] => --test [1] => ) ) [1] => Array ( [0] => thisshouldbehere ) ) Array ( [0] => Array ( [0] => Array ( [0] => --foo [1] => ) [1] => Array ( [0] => b [1] => ) [2] => Array ( [0] => a [1] => ) [3] => Array ( [0] => r [1] => ) [4] => Array ( [0] => r [1] => ) ) [1] => Array ( [0] => thisshouldbehere ) ) PK!`f3##BasicGraphTest.phpnu[ | // +-----------------------------------------------------------------------------+ // require_once dirname(__FILE__) . '/helper.inc'; /** * @access private */ class BasicGraph extends \PHPUnit\Framework\TestCase { var $_graph = null; function test_create_graph() { $this->_graph = new Structures_Graph(); $this->assertTrue(is_a($this->_graph, 'Structures_Graph')); } function test_add_node() { $this->_graph = new Structures_Graph(); $data = 1; $node = new Structures_Graph_Node($data); $this->_graph->addNode($node); $node = new Structures_Graph_Node($data); $this->_graph->addNode($node); $node = new Structures_Graph_Node($data); $this->_graph->addNode($node); $this->assertTrue(true); } function test_connect_node() { $this->_graph = new Structures_Graph(); $data = 1; $node1 = new Structures_Graph_Node($data); $node2 = new Structures_Graph_Node($data); $this->_graph->addNode($node1); $this->_graph->addNode($node2); $node1->connectTo($node2); $node =& $this->_graph->getNodes(); $node =& $node[0]; $node = $node->getNeighbours(); $node =& $node[0]; /* ZE1 == and === operators fail on $node,$node2 because of the recursion introduced by the _graph field in the Node object. So, we'll use the stupid method for reference testing */ $node = true; $this->assertTrue($node2); $node = false; $this->assertFalse($node2); } function test_data_references() { $this->_graph = new Structures_Graph(); $data = 1; $node = new Structures_Graph_Node(); $node->setData($data); $this->_graph->addNode($node); $data = 2; $dataInNode =& $this->_graph->getNodes(); $dataInNode =& $dataInNode[0]; $dataInNode =& $dataInNode->getData(); $this->assertEquals($data, $dataInNode); } function test_metadata_references() { $this->_graph = new Structures_Graph(); $data = 1; $node = new Structures_Graph_Node(); $node->setMetadata('5', $data); $data = 2; $dataInNode =& $node->getMetadata('5'); $this->assertEquals($data, $dataInNode); } function test_metadata_key_exists() { $this->_graph = new Structures_Graph(); $data = 1; $node = new Structures_Graph_Node(); $node->setMetadata('5', $data); $this->assertTrue($node->metadataKeyExists('5')); $this->assertFalse($node->metadataKeyExists('1')); } function test_directed_degree() { $this->_graph = new Structures_Graph(true); $node = array(); $node[] = new Structures_Graph_Node(); $node[] = new Structures_Graph_Node(); $node[] = new Structures_Graph_Node(); $this->_graph->addNode($node[0]); $this->_graph->addNode($node[1]); $this->_graph->addNode($node[2]); $this->assertEquals(0, $node[0]->inDegree(), 'inDegree test failed for node 0 with 0 arcs'); $this->assertEquals(0, $node[1]->inDegree(), 'inDegree test failed for node 1 with 0 arcs'); $this->assertEquals(0, $node[2]->inDegree(), 'inDegree test failed for node 2 with 0 arcs'); $this->assertEquals(0, $node[0]->outDegree(), 'outDegree test failed for node 0 with 0 arcs'); $this->assertEquals(0, $node[1]->outDegree(), 'outDegree test failed for node 1 with 0 arcs'); $this->assertEquals(0, $node[2]->outDegree(), 'outDegree test failed for node 2 with 0 arcs'); $node[0]->connectTo($node[1]); $this->assertEquals(0, $node[0]->inDegree(), 'inDegree test failed for node 0 with 1 arc'); $this->assertEquals(1, $node[1]->inDegree(), 'inDegree test failed for node 1 with 1 arc'); $this->assertEquals(0, $node[2]->inDegree(), 'inDegree test failed for node 2 with 1 arc'); $this->assertEquals(1, $node[0]->outDegree(), 'outDegree test failed for node 0 with 1 arc'); $this->assertEquals(0, $node[1]->outDegree(), 'outDegree test failed for node 1 with 1 arc'); $this->assertEquals(0, $node[2]->outDegree(), 'outDegree test failed for node 2 with 1 arc'); $node[0]->connectTo($node[2]); $this->assertEquals(0, $node[0]->inDegree(), 'inDegree test failed for node 0 with 2 arcs'); $this->assertEquals(1, $node[1]->inDegree(), 'inDegree test failed for node 1 with 2 arcs'); $this->assertEquals(1, $node[2]->inDegree(), 'inDegree test failed for node 2 with 2 arcs'); $this->assertEquals(2, $node[0]->outDegree(), 'outDegree test failed for node 0 with 2 arcs'); $this->assertEquals(0, $node[1]->outDegree(), 'outDegree test failed for node 1 with 2 arcs'); $this->assertEquals(0, $node[2]->outDegree(), 'outDegree test failed for node 2 with 2 arcs'); } function test_undirected_degree() { $this->_graph = new Structures_Graph(false); $node = array(); $node[] = new Structures_Graph_Node(); $node[] = new Structures_Graph_Node(); $node[] = new Structures_Graph_Node(); $this->_graph->addNode($node[0]); $this->_graph->addNode($node[1]); $this->_graph->addNode($node[2]); $this->assertEquals(0, $node[0]->inDegree(), 'inDegree test failed for node 0 with 0 arcs'); $this->assertEquals(0, $node[1]->inDegree(), 'inDegree test failed for node 1 with 0 arcs'); $this->assertEquals(0, $node[2]->inDegree(), 'inDegree test failed for node 2 with 0 arcs'); $this->assertEquals(0, $node[0]->outDegree(), 'outDegree test failed for node 0 with 0 arcs'); $this->assertEquals(0, $node[1]->outDegree(), 'outDegree test failed for node 1 with 0 arcs'); $this->assertEquals(0, $node[2]->outDegree(), 'outDegree test failed for node 2 with 0 arcs'); $node[0]->connectTo($node[1]); $this->assertEquals(1, $node[0]->inDegree(), 'inDegree test failed for node 0 with 1 arc'); $this->assertEquals(1, $node[1]->inDegree(), 'inDegree test failed for node 1 with 1 arc'); $this->assertEquals(0, $node[2]->inDegree(), 'inDegree test failed for node 2 with 1 arc'); $this->assertEquals(1, $node[0]->outDegree(), 'outDegree test failed for node 0 with 1 arc'); $this->assertEquals(1, $node[1]->outDegree(), 'outDegree test failed for node 1 with 1 arc'); $this->assertEquals(0, $node[2]->outDegree(), 'outDegree test failed for node 2 with 1 arc'); $node[0]->connectTo($node[2]); $this->assertEquals(2, $node[0]->inDegree(), 'inDegree test failed for node 0 with 2 arcs'); $this->assertEquals(1, $node[1]->inDegree(), 'inDegree test failed for node 1 with 2 arcs'); $this->assertEquals(1, $node[2]->inDegree(), 'inDegree test failed for node 2 with 2 arcs'); $this->assertEquals(2, $node[0]->outDegree(), 'outDegree test failed for node 0 with 2 arcs'); $this->assertEquals(1, $node[1]->outDegree(), 'outDegree test failed for node 1 with 2 arcs'); $this->assertEquals(1, $node[2]->outDegree(), 'outDegree test failed for node 2 with 2 arcs'); } } ?> PK! ;VVTopologicalSorterTest.phpnu[setData($name1); $graph->addNode($node1); $name11 = 'node11'; $node11 = new Structures_Graph_Node(); $node11->setData($name11); $graph->addNode($node11); $node1->connectTo($node11); $name12 = 'node12'; $node12 = new Structures_Graph_Node(); $node12->setData($name12); $graph->addNode($node12); $node1->connectTo($node12); $name121 = 'node121'; $node121 = new Structures_Graph_Node(); $node121->setData($name121); $graph->addNode($node121); $node12->connectTo($node121); $name2 = 'node2'; $node2 = new Structures_Graph_Node(); $node2->setData($name2); $graph->addNode($node2); $name21 = 'node21'; $node21 = new Structures_Graph_Node(); $node21->setData($name21); $graph->addNode($node21); $node2->connectTo($node21); $nodes = Structures_Graph_Manipulator_TopologicalSorter::sort($graph); $this->assertCount(2, $nodes[0]); $this->assertEquals('node1', $nodes[0][0]->getData()); $this->assertEquals('node2', $nodes[0][1]->getData()); $this->assertCount(3, $nodes[1]); $this->assertEquals('node11', $nodes[1][0]->getData()); $this->assertEquals('node12', $nodes[1][1]->getData()); $this->assertEquals('node21', $nodes[1][2]->getData()); $this->assertCount(1, $nodes[2]); $this->assertEquals('node121', $nodes[2][0]->getData()); } } ?> PK!eAcyclicTestTest.phpnu[addNode($node1); $node2 = new Structures_Graph_Node(); $graph->addNode($node2); $node1->connectTo($node2); $node3 = new Structures_Graph_Node(); $graph->addNode($node3); $node2->connectTo($node3); $node3->connectTo($node1); $this->assertFalse( Structures_Graph_Manipulator_AcyclicTest::isAcyclic($graph), 'Graph is cyclic' ); } public function testIsAcyclicTrue() { $graph = new Structures_Graph(); $node1 = new Structures_Graph_Node(); $graph->addNode($node1); $node2 = new Structures_Graph_Node(); $graph->addNode($node2); $node1->connectTo($node2); $node3 = new Structures_Graph_Node(); $graph->addNode($node3); $node2->connectTo($node3); $this->assertTrue( Structures_Graph_Manipulator_AcyclicTest::isAcyclic($graph), 'Graph is acyclic' ); } } ?> PK!݀tt helper.incnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Diff; use PHPUnit\Framework\TestCase; /** * @covers SebastianBergmann\Diff\Line */ final class LineTest extends TestCase { /** * @var Line */ private $line; protected function setUp(): void { $this->line = new Line; } public function testCanBeCreatedWithoutArguments(): void { $this->assertInstanceOf(Line::class, $this->line); } public function testTypeCanBeRetrieved(): void { $this->assertSame(Line::UNCHANGED, $this->line->getType()); } public function testContentCanBeRetrieved(): void { $this->assertSame('', $this->line->getContent()); } } PK!s'D fixtures/.editorconfignu[root = true PK!U$fixtures/patch.txtnu[diff --git a/Foo.php b/Foo.php index abcdefg..abcdefh 100644 --- a/Foo.php +++ b/Foo.php @@ -20,4 +20,5 @@ class Foo const ONE = 1; const TWO = 2; + const THREE = 3; const FOUR = 4; PK!s'D fixtures/out/.editorconfignu[root = true PK!DDfixtures/out/.gitignorenu[# reset all ignore rules to create sandbox for integration test !/**PK!Z$>//fixtures/serialized_diff.binnu[a:1:{i:0;O:27:"SebastianBergmann\Diff\Diff":3:{s:33:"SebastianBergmann\Diff\Difffrom";s:7:"old.txt";s:31:"SebastianBergmann\Diff\Diffto";s:7:"new.txt";s:35:"SebastianBergmann\Diff\Diffchunks";a:3:{i:0;O:28:"SebastianBergmann\Diff\Chunk":5:{s:35:"SebastianBergmann\Diff\Chunkstart";i:1;s:40:"SebastianBergmann\Diff\ChunkstartRange";i:3;s:33:"SebastianBergmann\Diff\Chunkend";i:1;s:38:"SebastianBergmann\Diff\ChunkendRange";i:4;s:35:"SebastianBergmann\Diff\Chunklines";a:4:{i:0;O:27:"SebastianBergmann\Diff\Line":2:{s:33:"SebastianBergmann\Diff\Linetype";i:1;s:36:"SebastianBergmann\Diff\Linecontent";s:7:"2222111";}i:1;O:27:"SebastianBergmann\Diff\Line":2:{s:33:"SebastianBergmann\Diff\Linetype";i:3;s:36:"SebastianBergmann\Diff\Linecontent";s:7:"1111111";}i:2;O:27:"SebastianBergmann\Diff\Line":2:{s:33:"SebastianBergmann\Diff\Linetype";i:3;s:36:"SebastianBergmann\Diff\Linecontent";s:7:"1111111";}i:3;O:27:"SebastianBergmann\Diff\Line":2:{s:33:"SebastianBergmann\Diff\Linetype";i:3;s:36:"SebastianBergmann\Diff\Linecontent";s:7:"1111111";}}}i:1;O:28:"SebastianBergmann\Diff\Chunk":5:{s:35:"SebastianBergmann\Diff\Chunkstart";i:5;s:40:"SebastianBergmann\Diff\ChunkstartRange";i:10;s:33:"SebastianBergmann\Diff\Chunkend";i:6;s:38:"SebastianBergmann\Diff\ChunkendRange";i:8;s:35:"SebastianBergmann\Diff\Chunklines";a:11:{i:0;O:27:"SebastianBergmann\Diff\Line":2:{s:33:"SebastianBergmann\Diff\Linetype";i:3;s:36:"SebastianBergmann\Diff\Linecontent";s:7:"1111111";}i:1;O:27:"SebastianBergmann\Diff\Line":2:{s:33:"SebastianBergmann\Diff\Linetype";i:3;s:36:"SebastianBergmann\Diff\Linecontent";s:7:"1111111";}i:2;O:27:"SebastianBergmann\Diff\Line":2:{s:33:"SebastianBergmann\Diff\Linetype";i:3;s:36:"SebastianBergmann\Diff\Linecontent";s:7:"1111111";}i:3;O:27:"SebastianBergmann\Diff\Line":2:{s:33:"SebastianBergmann\Diff\Linetype";i:3;s:36:"SebastianBergmann\Diff\Linecontent";s:8:"+1121211";}i:4;O:27:"SebastianBergmann\Diff\Line":2:{s:33:"SebastianBergmann\Diff\Linetype";i:3;s:36:"SebastianBergmann\Diff\Linecontent";s:7:"1111111";}i:5;O:27:"SebastianBergmann\Diff\Line":2:{s:33:"SebastianBergmann\Diff\Linetype";i:3;s:36:"SebastianBergmann\Diff\Linecontent";s:8:"-1111111";}i:6;O:27:"SebastianBergmann\Diff\Line":2:{s:33:"SebastianBergmann\Diff\Linetype";i:3;s:36:"SebastianBergmann\Diff\Linecontent";s:8:"-1111111";}i:7;O:27:"SebastianBergmann\Diff\Line":2:{s:33:"SebastianBergmann\Diff\Linetype";i:3;s:36:"SebastianBergmann\Diff\Linecontent";s:8:"-2222222";}i:8;O:27:"SebastianBergmann\Diff\Line":2:{s:33:"SebastianBergmann\Diff\Linetype";i:3;s:36:"SebastianBergmann\Diff\Linecontent";s:7:"2222222";}i:9;O:27:"SebastianBergmann\Diff\Line":2:{s:33:"SebastianBergmann\Diff\Linetype";i:3;s:36:"SebastianBergmann\Diff\Linecontent";s:7:"2222222";}i:10;O:27:"SebastianBergmann\Diff\Line":2:{s:33:"SebastianBergmann\Diff\Linetype";i:3;s:36:"SebastianBergmann\Diff\Linecontent";s:7:"2222222";}}}i:2;O:28:"SebastianBergmann\Diff\Chunk":5:{s:35:"SebastianBergmann\Diff\Chunkstart";i:17;s:40:"SebastianBergmann\Diff\ChunkstartRange";i:5;s:33:"SebastianBergmann\Diff\Chunkend";i:16;s:38:"SebastianBergmann\Diff\ChunkendRange";i:6;s:35:"SebastianBergmann\Diff\Chunklines";a:6:{i:0;O:27:"SebastianBergmann\Diff\Line":2:{s:33:"SebastianBergmann\Diff\Linetype";i:3;s:36:"SebastianBergmann\Diff\Linecontent";s:7:"2222222";}i:1;O:27:"SebastianBergmann\Diff\Line":2:{s:33:"SebastianBergmann\Diff\Linetype";i:3;s:36:"SebastianBergmann\Diff\Linecontent";s:7:"2222222";}i:2;O:27:"SebastianBergmann\Diff\Line":2:{s:33:"SebastianBergmann\Diff\Linetype";i:3;s:36:"SebastianBergmann\Diff\Linecontent";s:7:"2222222";}i:3;O:27:"SebastianBergmann\Diff\Line":2:{s:33:"SebastianBergmann\Diff\Linetype";i:3;s:36:"SebastianBergmann\Diff\Linecontent";s:8:"+2122212";}i:4;O:27:"SebastianBergmann\Diff\Line":2:{s:33:"SebastianBergmann\Diff\Linetype";i:3;s:36:"SebastianBergmann\Diff\Linecontent";s:7:"2222222";}i:5;O:27:"SebastianBergmann\Diff\Line":2:{s:33:"SebastianBergmann\Diff\Linetype";i:3;s:36:"SebastianBergmann\Diff\Linecontent";s:7:"2222222";}}}}}}PK!C6fixtures/UnifiedDiffAssertTraitIntegrationTest/1_a.txtnu[aPK!2##6fixtures/UnifiedDiffAssertTraitIntegrationTest/2_b.txtnu[a a a a a a a a a a b a a a a a a cPK!&/EE6fixtures/UnifiedDiffAssertTraitIntegrationTest/2_a.txtnu[a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a aPK!6fixtures/UnifiedDiffAssertTraitIntegrationTest/1_b.txtnu[PK!@k鐚fixtures/patch2.txtnu[diff --git a/Foo.php b/Foo.php index abcdefg..abcdefh 100644 --- a/Foo.php +++ b/Foo.php @@ -20,4 +20,5 @@ class Foo const ONE = 1; const TWO = 2; + const THREE = 3; const FOUR = 4; @@ -320,4 +320,5 @@ class Foo const A = 'A'; const B = 'B'; + const C = 'C'; const D = 'D'; @@ -600,4 +600,5 @@ class Foo public function doSomething() { + return 'foo'; } PK!Y0MÒ ChunkTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Diff; use PHPUnit\Framework\TestCase; /** * @covers SebastianBergmann\Diff\Chunk */ final class ChunkTest extends TestCase { /** * @var Chunk */ private $chunk; protected function setUp(): void { $this->chunk = new Chunk; } public function testHasInitiallyNoLines(): void { $this->assertSame([], $this->chunk->getLines()); } public function testCanBeCreatedWithoutArguments(): void { $this->assertInstanceOf(Chunk::class, $this->chunk); } public function testStartCanBeRetrieved(): void { $this->assertSame(0, $this->chunk->getStart()); } public function testStartRangeCanBeRetrieved(): void { $this->assertSame(1, $this->chunk->getStartRange()); } public function testEndCanBeRetrieved(): void { $this->assertSame(0, $this->chunk->getEnd()); } public function testEndRangeCanBeRetrieved(): void { $this->assertSame(1, $this->chunk->getEndRange()); } public function testLinesCanBeRetrieved(): void { $this->assertSame([], $this->chunk->getLines()); } public function testLinesCanBeSet(): void { $lines = [new Line(Line::ADDED, 'added'), new Line(Line::REMOVED, 'removed')]; $this->chunk->setLines($lines); $this->assertSame($lines, $this->chunk->getLines()); } } PK!..DifferTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Diff; use PHPUnit\Framework\TestCase; use SebastianBergmann\Diff\Output\UnifiedDiffOutputBuilder; /** * @covers SebastianBergmann\Diff\Differ * @covers SebastianBergmann\Diff\Output\UnifiedDiffOutputBuilder * * @uses SebastianBergmann\Diff\MemoryEfficientLongestCommonSubsequenceCalculator * @uses SebastianBergmann\Diff\TimeEfficientLongestCommonSubsequenceCalculator * @uses SebastianBergmann\Diff\Output\AbstractChunkOutputBuilder */ final class DifferTest extends TestCase { /** * @var Differ */ private $differ; protected function setUp(): void { $this->differ = new Differ; } /** * @param array $expected * @param array|string $from * @param array|string $to * * @dataProvider arrayProvider */ public function testArrayRepresentationOfDiffCanBeRenderedUsingTimeEfficientLcsImplementation(array $expected, $from, $to): void { $this->assertSame($expected, $this->differ->diffToArray($from, $to, new TimeEfficientLongestCommonSubsequenceCalculator)); } /** * @param string $expected * @param string $from * @param string $to * * @dataProvider textProvider */ public function testTextRepresentationOfDiffCanBeRenderedUsingTimeEfficientLcsImplementation(string $expected, string $from, string $to): void { $this->assertSame($expected, $this->differ->diff($from, $to, new TimeEfficientLongestCommonSubsequenceCalculator)); } /** * @param array $expected * @param array|string $from * @param array|string $to * * @dataProvider arrayProvider */ public function testArrayRepresentationOfDiffCanBeRenderedUsingMemoryEfficientLcsImplementation(array $expected, $from, $to): void { $this->assertSame($expected, $this->differ->diffToArray($from, $to, new MemoryEfficientLongestCommonSubsequenceCalculator)); } /** * @param string $expected * @param string $from * @param string $to * * @dataProvider textProvider */ public function testTextRepresentationOfDiffCanBeRenderedUsingMemoryEfficientLcsImplementation(string $expected, string $from, string $to): void { $this->assertSame($expected, $this->differ->diff($from, $to, new MemoryEfficientLongestCommonSubsequenceCalculator)); } public function testTypesOtherThanArrayAndStringCanBePassed(): void { $this->assertSame( "--- Original\n+++ New\n@@ @@\n-1\n+2\n", $this->differ->diff(1, 2) ); } public function testArrayDiffs(): void { $this->assertSame( '--- Original +++ New @@ @@ -one +two ', $this->differ->diff(['one'], ['two']) ); } public function arrayProvider(): array { return [ [ [ ['a', Differ::REMOVED], ['b', Differ::ADDED], ], 'a', 'b', ], [ [ ['ba', Differ::REMOVED], ['bc', Differ::ADDED], ], 'ba', 'bc', ], [ [ ['ab', Differ::REMOVED], ['cb', Differ::ADDED], ], 'ab', 'cb', ], [ [ ['abc', Differ::REMOVED], ['adc', Differ::ADDED], ], 'abc', 'adc', ], [ [ ['ab', Differ::REMOVED], ['abc', Differ::ADDED], ], 'ab', 'abc', ], [ [ ['bc', Differ::REMOVED], ['abc', Differ::ADDED], ], 'bc', 'abc', ], [ [ ['abc', Differ::REMOVED], ['abbc', Differ::ADDED], ], 'abc', 'abbc', ], [ [ ['abcdde', Differ::REMOVED], ['abcde', Differ::ADDED], ], 'abcdde', 'abcde', ], 'same start' => [ [ [17, Differ::OLD], ['b', Differ::REMOVED], ['d', Differ::ADDED], ], [30 => 17, 'a' => 'b'], [30 => 17, 'c' => 'd'], ], 'same end' => [ [ [1, Differ::REMOVED], [2, Differ::ADDED], ['b', Differ::OLD], ], [1 => 1, 'a' => 'b'], [1 => 2, 'a' => 'b'], ], 'same start (2), same end (1)' => [ [ [17, Differ::OLD], [2, Differ::OLD], [4, Differ::REMOVED], ['a', Differ::ADDED], [5, Differ::ADDED], ['x', Differ::OLD], ], [30 => 17, 1 => 2, 2 => 4, 'z' => 'x'], [30 => 17, 1 => 2, 3 => 'a', 2 => 5, 'z' => 'x'], ], 'same' => [ [ ['x', Differ::OLD], ], ['z' => 'x'], ['z' => 'x'], ], 'diff' => [ [ ['y', Differ::REMOVED], ['x', Differ::ADDED], ], ['x' => 'y'], ['z' => 'x'], ], 'diff 2' => [ [ ['y', Differ::REMOVED], ['b', Differ::REMOVED], ['x', Differ::ADDED], ['d', Differ::ADDED], ], ['x' => 'y', 'a' => 'b'], ['z' => 'x', 'c' => 'd'], ], 'test line diff detection' => [ [ [ "#Warning: Strings contain different line endings!\n", Differ::DIFF_LINE_END_WARNING, ], [ " [ [ [ "#Warning: Strings contain different line endings!\n", Differ::DIFF_LINE_END_WARNING, ], [ "expectException(InvalidArgumentException::class); $this->expectExceptionMessageRegExp('#^"from" must be an array or string\.$#'); $this->differ->diffToArray(null, ''); } public function testDiffInvalidToType(): void { $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessageRegExp('#^"to" must be an array or string\.$#'); $this->differ->diffToArray('', new \stdClass); } /** * @param array $expected * @param string $input * * @dataProvider provideSplitStringByLinesCases */ public function testSplitStringByLines(array $expected, string $input): void { $reflection = new \ReflectionObject($this->differ); $method = $reflection->getMethod('splitStringByLines'); $method->setAccessible(true); $this->assertSame($expected, $method->invoke($this->differ, $input)); } public function provideSplitStringByLinesCases(): array { return [ [ [], '', ], [ ['a'], 'a', ], [ ["a\n"], "a\n", ], [ ["a\r"], "a\r", ], [ ["a\r\n"], "a\r\n", ], [ ["\n"], "\n", ], [ ["\r"], "\r", ], [ ["\r\n"], "\r\n", ], [ [ "A\n", "B\n", "\n", "C\n", ], "A\nB\n\nC\n", ], [ [ "A\r\n", "B\n", "\n", "C\r", ], "A\r\nB\n\nC\r", ], [ [ "\n", "A\r\n", "B\n", "\n", 'C', ], "\nA\r\nB\n\nC", ], ]; } public function testConstructorInvalidArgInt(): void { $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessageRegExp('/^Expected builder to be an instance of DiffOutputBuilderInterface, or a string, got integer "1"\.$/'); new Differ(1); } public function testConstructorInvalidArgObject(): void { $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessageRegExp('/^Expected builder to be an instance of DiffOutputBuilderInterface, or a string, got instance of "SplFileInfo"\.$/'); new Differ(new \SplFileInfo(__FILE__)); } } PK!8 ParserTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Diff; use PHPUnit\Framework\TestCase; use SebastianBergmann\Diff\Utils\FileUtils; /** * @covers SebastianBergmann\Diff\Parser * * @uses SebastianBergmann\Diff\Chunk * @uses SebastianBergmann\Diff\Diff * @uses SebastianBergmann\Diff\Line */ final class ParserTest extends TestCase { /** * @var Parser */ private $parser; protected function setUp(): void { $this->parser = new Parser; } public function testParse(): void { $content = FileUtils::getFileContent(__DIR__ . '/fixtures/patch.txt'); $diffs = $this->parser->parse($content); $this->assertContainsOnlyInstancesOf(Diff::class, $diffs); $this->assertCount(1, $diffs); $chunks = $diffs[0]->getChunks(); $this->assertContainsOnlyInstancesOf(Chunk::class, $chunks); $this->assertCount(1, $chunks); $this->assertSame(20, $chunks[0]->getStart()); $this->assertCount(4, $chunks[0]->getLines()); } public function testParseWithMultipleChunks(): void { $content = FileUtils::getFileContent(__DIR__ . '/fixtures/patch2.txt'); $diffs = $this->parser->parse($content); $this->assertCount(1, $diffs); $chunks = $diffs[0]->getChunks(); $this->assertCount(3, $chunks); $this->assertSame(20, $chunks[0]->getStart()); $this->assertSame(320, $chunks[1]->getStart()); $this->assertSame(600, $chunks[2]->getStart()); $this->assertCount(5, $chunks[0]->getLines()); $this->assertCount(5, $chunks[1]->getLines()); $this->assertCount(4, $chunks[2]->getLines()); } public function testParseWithRemovedLines(): void { $content = <<parser->parse($content); $this->assertContainsOnlyInstancesOf(Diff::class, $diffs); $this->assertCount(1, $diffs); $chunks = $diffs[0]->getChunks(); $this->assertContainsOnlyInstancesOf(Chunk::class, $chunks); $this->assertCount(1, $chunks); $chunk = $chunks[0]; $this->assertSame(49, $chunk->getStart()); $this->assertSame(49, $chunk->getEnd()); $this->assertSame(9, $chunk->getStartRange()); $this->assertSame(8, $chunk->getEndRange()); $lines = $chunk->getLines(); $this->assertContainsOnlyInstancesOf(Line::class, $lines); $this->assertCount(2, $lines); /** @var Line $line */ $line = $lines[0]; $this->assertSame('A', $line->getContent()); $this->assertSame(Line::UNCHANGED, $line->getType()); $line = $lines[1]; $this->assertSame('B', $line->getContent()); $this->assertSame(Line::REMOVED, $line->getType()); } public function testParseDiffForMulitpleFiles(): void { $content = <<parser->parse($content); $this->assertCount(2, $diffs); /** @var Diff $diff */ $diff = $diffs[0]; $this->assertSame('a/Test.txt', $diff->getFrom()); $this->assertSame('b/Test.txt', $diff->getTo()); $this->assertCount(1, $diff->getChunks()); $diff = $diffs[1]; $this->assertSame('a/Test2.txt', $diff->getFrom()); $this->assertSame('b/Test2.txt', $diff->getTo()); $this->assertCount(1, $diff->getChunks()); } /** * @param string $diff * @param Diff[] $expected * * @dataProvider diffProvider */ public function testParser(string $diff, array $expected): void { $result = $this->parser->parse($diff); $this->assertEquals($expected, $result); } public function diffProvider(): array { return [ [ "--- old.txt 2014-11-04 08:51:02.661868729 +0300\n+++ new.txt 2014-11-04 08:51:02.665868730 +0300\n@@ -1,3 +1,4 @@\n+2222111\n 1111111\n 1111111\n 1111111\n@@ -5,10 +6,8 @@\n 1111111\n 1111111\n 1111111\n +1121211\n 1111111\n -1111111\n -1111111\n -2222222\n 2222222\n 2222222\n 2222222\n@@ -17,5 +16,6 @@\n 2222222\n 2222222\n 2222222\n +2122212\n 2222222\n 2222222\n", \unserialize(FileUtils::getFileContent(__DIR__ . '/fixtures/serialized_diff.bin')), ], ]; } } PK!uu DiffTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Diff; use PHPUnit\Framework\TestCase; /** * @covers SebastianBergmann\Diff\Diff * * @uses SebastianBergmann\Diff\Chunk */ final class DiffTest extends TestCase { public function testGettersAfterConstructionWithDefault(): void { $from = 'line1a'; $to = 'line2a'; $diff = new Diff($from, $to); $this->assertSame($from, $diff->getFrom()); $this->assertSame($to, $diff->getTo()); $this->assertSame([], $diff->getChunks(), 'Expect chunks to be default value "array()".'); } public function testGettersAfterConstructionWithChunks(): void { $from = 'line1b'; $to = 'line2b'; $chunks = [new Chunk(), new Chunk(2, 3)]; $diff = new Diff($from, $to, $chunks); $this->assertSame($from, $diff->getFrom()); $this->assertSame($to, $diff->getTo()); $this->assertSame($chunks, $diff->getChunks(), 'Expect chunks to be passed value.'); } public function testSetChunksAfterConstruction(): void { $diff = new Diff('line1c', 'line2c'); $this->assertSame([], $diff->getChunks(), 'Expect chunks to be default value "array()".'); $chunks = [new Chunk(), new Chunk(2, 3)]; $diff->setChunks($chunks); $this->assertSame($chunks, $diff->getChunks(), 'Expect chunks to be passed value.'); } } PK!$yy#TimeEfficientImplementationTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Diff; /** * @covers SebastianBergmann\Diff\TimeEfficientLongestCommonSubsequenceCalculator */ final class TimeEfficientImplementationTest extends LongestCommonSubsequenceTest { protected function createImplementation(): LongestCommonSubsequenceCalculator { return new TimeEfficientLongestCommonSubsequenceCalculator; } } PK!kUtils/FileUtils.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Diff\Utils; final class FileUtils { public static function getFileContent(string $file): string { $content = @\file_get_contents($file); if (false === $content) { $error = \error_get_last(); throw new \RuntimeException(\sprintf( 'Failed to read content of file "%s".%s', $file, $error ? ' ' . $error['message'] : '' )); } return $content; } } PK!d,d,$Utils/UnifiedDiffAssertTraitTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Diff\Utils; use PHPUnit\Framework\TestCase; /** * @covers SebastianBergmann\Diff\Utils\UnifiedDiffAssertTrait */ final class UnifiedDiffAssertTraitTest extends TestCase { use UnifiedDiffAssertTrait; /** * @param string $diff * * @dataProvider provideValidCases */ public function testValidCases(string $diff): void { $this->assertValidUnifiedDiffFormat($diff); } public function provideValidCases(): array { return [ [ '--- Original +++ New @@ -8 +8 @@ -Z +U ', ], [ '--- Original +++ New @@ -8 +8 @@ -Z +U @@ -15 +15 @@ -X +V ', ], 'empty diff. is valid' => [ '', ], ]; } public function testNoLinebreakEnd(): void { $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Expected diff to end with a line break, got "C".', '#'))); $this->assertValidUnifiedDiffFormat("A\nB\nC"); } public function testInvalidStartWithoutHeader(): void { $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote("Expected line to start with '@', '-' or '+', got \"A\n\". Line 1.", '#'))); $this->assertValidUnifiedDiffFormat("A\n"); } public function testInvalidStartHeader1(): void { $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote("Line 1 indicates a header, so line 2 must start with \"+++\".\nLine 1: \"--- A\n\"\nLine 2: \"+ 1\n\".", '#'))); $this->assertValidUnifiedDiffFormat("--- A\n+ 1\n"); } public function testInvalidStartHeader2(): void { $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote("Header line does not match expected pattern, got \"+++ file X\n\". Line 2.", '#'))); $this->assertValidUnifiedDiffFormat("--- A\n+++ file\tX\n"); } public function testInvalidStartHeader3(): void { $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Date of header line does not match expected pattern, got "[invalid date]". Line 1.', '#'))); $this->assertValidUnifiedDiffFormat( "--- Original\t[invalid date] +++ New @@ -1,2 +1,2 @@ -A +B " . ' ' ); } public function testInvalidStartHeader4(): void { $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote("Expected header line to start with \"+++ \", got \"+++INVALID\n\". Line 2.", '#'))); $this->assertValidUnifiedDiffFormat( '--- Original +++INVALID @@ -1,2 +1,2 @@ -A +B ' . ' ' ); } public function testInvalidLine1(): void { $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote("Expected line to start with '@', '-' or '+', got \"1\n\". Line 5.", '#'))); $this->assertValidUnifiedDiffFormat( '--- Original +++ New @@ -8 +8 @@ -Z 1 +U ' ); } public function testInvalidLine2(): void { $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Expected string length of minimal 2, got 1. Line 4.', '#'))); $this->assertValidUnifiedDiffFormat( '--- Original +++ New @@ -8 +8 @@ ' ); } public function testHunkInvalidFormat(): void { $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote("Hunk header line does not match expected pattern, got \"@@ INVALID -1,1 +1,1 @@\n\". Line 3.", '#'))); $this->assertValidUnifiedDiffFormat( '--- Original +++ New @@ INVALID -1,1 +1,1 @@ -Z +U ' ); } public function testHunkOverlapFrom(): void { $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Unexpected new hunk; "from" (\'-\') start overlaps previous hunk. Line 6.', '#'))); $this->assertValidUnifiedDiffFormat( '--- Original +++ New @@ -8,1 +8,1 @@ -Z +U @@ -7,1 +9,1 @@ -Z +U ' ); } public function testHunkOverlapTo(): void { $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Unexpected new hunk; "to" (\'+\') start overlaps previous hunk. Line 6.', '#'))); $this->assertValidUnifiedDiffFormat( '--- Original +++ New @@ -8,1 +8,1 @@ -Z +U @@ -17,1 +7,1 @@ -Z +U ' ); } public function testExpectHunk1(): void { $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Expected hunk start (\'@\'), got "+". Line 6.', '#'))); $this->assertValidUnifiedDiffFormat( '--- Original +++ New @@ -8 +8 @@ -Z +U +O ' ); } public function testExpectHunk2(): void { $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Unexpected hunk start (\'@\'). Line 6.', '#'))); $this->assertValidUnifiedDiffFormat( '--- Original +++ New @@ -8,12 +8,12 @@ ' . ' ' . ' @@ -38,12 +48,12 @@ ' ); } public function testMisplacedLineAfterComments1(): void { $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Unexpected line as 2 "No newline" markers have found, ". Line 8.', '#'))); $this->assertValidUnifiedDiffFormat( '--- Original +++ New @@ -8 +8 @@ -Z \ No newline at end of file +U \ No newline at end of file +A ' ); } public function testMisplacedLineAfterComments2(): void { $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Unexpected line as 2 "No newline" markers have found, ". Line 7.', '#'))); $this->assertValidUnifiedDiffFormat( '--- Original +++ New @@ -8 +8 @@ +U \ No newline at end of file \ No newline at end of file \ No newline at end of file ' ); } public function testMisplacedLineAfterComments3(): void { $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Unexpected line as 2 "No newline" markers have found, ". Line 7.', '#'))); $this->assertValidUnifiedDiffFormat( '--- Original +++ New @@ -8 +8 @@ +U \ No newline at end of file \ No newline at end of file +A ' ); } public function testMisplacedComment(): void { $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Unexpected "\ No newline at end of file", it must be preceded by \'+\' or \'-\' line. Line 1.', '#'))); $this->assertValidUnifiedDiffFormat( '\ No newline at end of file ' ); } public function testUnexpectedDuplicateNoNewLineEOF(): void { $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Unexpected "\\ No newline at end of file", "\\" was already closed. Line 8.', '#'))); $this->assertValidUnifiedDiffFormat( '--- Original +++ New @@ -8,12 +8,12 @@ ' . ' ' . ' \ No newline at end of file ' . ' \ No newline at end of file ' ); } public function testFromAfterClose(): void { $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Not expected from (\'-\'), already closed by "\ No newline at end of file". Line 6.', '#'))); $this->assertValidUnifiedDiffFormat( '--- Original +++ New @@ -8,12 +8,12 @@ -A \ No newline at end of file -A \ No newline at end of file ' ); } public function testSameAfterFromClose(): void { $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Not expected same (\' \'), \'-\' already closed by "\ No newline at end of file". Line 6.', '#'))); $this->assertValidUnifiedDiffFormat( '--- Original +++ New @@ -8,12 +8,12 @@ -A \ No newline at end of file A \ No newline at end of file ' ); } public function testToAfterClose(): void { $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Not expected to (\'+\'), already closed by "\ No newline at end of file". Line 6.', '#'))); $this->assertValidUnifiedDiffFormat( '--- Original +++ New @@ -8,12 +8,12 @@ +A \ No newline at end of file +A \ No newline at end of file ' ); } public function testSameAfterToClose(): void { $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Not expected same (\' \'), \'+\' already closed by "\ No newline at end of file". Line 6.', '#'))); $this->assertValidUnifiedDiffFormat( '--- Original +++ New @@ -8,12 +8,12 @@ +A \ No newline at end of file A \ No newline at end of file ' ); } public function testUnexpectedEOFFromMissingLines(): void { $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Unexpected EOF, number of lines in hunk "from" (\'-\')) mismatched. Line 7.', '#'))); $this->assertValidUnifiedDiffFormat( '--- Original +++ New @@ -8,19 +7,2 @@ -A +B ' . ' ' ); } public function testUnexpectedEOFToMissingLines(): void { $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Unexpected EOF, number of lines in hunk "to" (\'+\')) mismatched. Line 7.', '#'))); $this->assertValidUnifiedDiffFormat( '--- Original +++ New @@ -8,2 +7,3 @@ -A +B ' . ' ' ); } public function testUnexpectedEOFBothFromAndToMissingLines(): void { $this->expectException(\UnexpectedValueException::class); $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Unexpected EOF, number of lines in hunk "from" (\'-\')) and "to" (\'+\') mismatched. Line 7.', '#'))); $this->assertValidUnifiedDiffFormat( '--- Original +++ New @@ -1,12 +1,14 @@ -A +B ' . ' ' ); } } PK!"ڸ++ Utils/UnifiedDiffAssertTrait.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Diff\Utils; trait UnifiedDiffAssertTrait { /** * @param string $diff * * @throws \UnexpectedValueException */ public function assertValidUnifiedDiffFormat(string $diff): void { if ('' === $diff) { $this->addToAssertionCount(1); return; } // test diff ends with a line break $last = \substr($diff, -1); if ("\n" !== $last && "\r" !== $last) { throw new \UnexpectedValueException(\sprintf('Expected diff to end with a line break, got "%s".', $last)); } $lines = \preg_split('/(.*\R)/', $diff, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); $lineCount = \count($lines); $lineNumber = $diffLineFromNumber = $diffLineToNumber = 1; $fromStart = $fromTillOffset = $toStart = $toTillOffset = -1; $expectHunkHeader = true; // check for header if ($lineCount > 1) { $this->unifiedDiffAssertLinePrefix($lines[0], 'Line 1.'); $this->unifiedDiffAssertLinePrefix($lines[1], 'Line 2.'); if ('---' === \substr($lines[0], 0, 3)) { if ('+++' !== \substr($lines[1], 0, 3)) { throw new \UnexpectedValueException(\sprintf("Line 1 indicates a header, so line 2 must start with \"+++\".\nLine 1: \"%s\"\nLine 2: \"%s\".", $lines[0], $lines[1])); } $this->unifiedDiffAssertHeaderLine($lines[0], '--- ', 'Line 1.'); $this->unifiedDiffAssertHeaderLine($lines[1], '+++ ', 'Line 2.'); $lineNumber = 3; } } $endOfLineTypes = []; $diffClosed = false; // assert format of lines, get all hunks, test the line numbers for (; $lineNumber <= $lineCount; ++$lineNumber) { if ($diffClosed) { throw new \UnexpectedValueException(\sprintf('Unexpected line as 2 "No newline" markers have found, ". Line %d.', $lineNumber)); } $line = $lines[$lineNumber - 1]; // line numbers start by 1, array index at 0 $type = $this->unifiedDiffAssertLinePrefix($line, \sprintf('Line %d.', $lineNumber)); if ($expectHunkHeader && '@' !== $type && '\\' !== $type) { throw new \UnexpectedValueException(\sprintf('Expected hunk start (\'@\'), got "%s". Line %d.', $type, $lineNumber)); } if ('@' === $type) { if (!$expectHunkHeader) { throw new \UnexpectedValueException(\sprintf('Unexpected hunk start (\'@\'). Line %d.', $lineNumber)); } $previousHunkFromEnd = $fromStart + $fromTillOffset; $previousHunkTillEnd = $toStart + $toTillOffset; [$fromStart, $fromTillOffset, $toStart, $toTillOffset] = $this->unifiedDiffAssertHunkHeader($line, \sprintf('Line %d.', $lineNumber)); // detect overlapping hunks if ($fromStart < $previousHunkFromEnd) { throw new \UnexpectedValueException(\sprintf('Unexpected new hunk; "from" (\'-\') start overlaps previous hunk. Line %d.', $lineNumber)); } if ($toStart < $previousHunkTillEnd) { throw new \UnexpectedValueException(\sprintf('Unexpected new hunk; "to" (\'+\') start overlaps previous hunk. Line %d.', $lineNumber)); } /* valid states; hunks touches against each other: $fromStart === $previousHunkFromEnd $toStart === $previousHunkTillEnd */ $diffLineFromNumber = $fromStart; $diffLineToNumber = $toStart; $expectHunkHeader = false; continue; } if ('-' === $type) { if (isset($endOfLineTypes['-'])) { throw new \UnexpectedValueException(\sprintf('Not expected from (\'-\'), already closed by "\\ No newline at end of file". Line %d.', $lineNumber)); } ++$diffLineFromNumber; } elseif ('+' === $type) { if (isset($endOfLineTypes['+'])) { throw new \UnexpectedValueException(\sprintf('Not expected to (\'+\'), already closed by "\\ No newline at end of file". Line %d.', $lineNumber)); } ++$diffLineToNumber; } elseif (' ' === $type) { if (isset($endOfLineTypes['-'])) { throw new \UnexpectedValueException(\sprintf('Not expected same (\' \'), \'-\' already closed by "\\ No newline at end of file". Line %d.', $lineNumber)); } if (isset($endOfLineTypes['+'])) { throw new \UnexpectedValueException(\sprintf('Not expected same (\' \'), \'+\' already closed by "\\ No newline at end of file". Line %d.', $lineNumber)); } ++$diffLineFromNumber; ++$diffLineToNumber; } elseif ('\\' === $type) { if (!isset($lines[$lineNumber - 2])) { throw new \UnexpectedValueException(\sprintf('Unexpected "\\ No newline at end of file", it must be preceded by \'+\' or \'-\' line. Line %d.', $lineNumber)); } $previousType = $this->unifiedDiffAssertLinePrefix($lines[$lineNumber - 2], \sprintf('Preceding line of "\\ No newline at end of file" of unexpected format. Line %d.', $lineNumber)); if (isset($endOfLineTypes[$previousType])) { throw new \UnexpectedValueException(\sprintf('Unexpected "\\ No newline at end of file", "%s" was already closed. Line %d.', $type, $lineNumber)); } $endOfLineTypes[$previousType] = true; $diffClosed = \count($endOfLineTypes) > 1; } else { // internal state error throw new \RuntimeException(\sprintf('Unexpected line type "%s" Line %d.', $type, $lineNumber)); } $expectHunkHeader = $diffLineFromNumber === ($fromStart + $fromTillOffset) && $diffLineToNumber === ($toStart + $toTillOffset) ; } if ( $diffLineFromNumber !== ($fromStart + $fromTillOffset) && $diffLineToNumber !== ($toStart + $toTillOffset) ) { throw new \UnexpectedValueException(\sprintf('Unexpected EOF, number of lines in hunk "from" (\'-\')) and "to" (\'+\') mismatched. Line %d.', $lineNumber)); } if ($diffLineFromNumber !== ($fromStart + $fromTillOffset)) { throw new \UnexpectedValueException(\sprintf('Unexpected EOF, number of lines in hunk "from" (\'-\')) mismatched. Line %d.', $lineNumber)); } if ($diffLineToNumber !== ($toStart + $toTillOffset)) { throw new \UnexpectedValueException(\sprintf('Unexpected EOF, number of lines in hunk "to" (\'+\')) mismatched. Line %d.', $lineNumber)); } $this->addToAssertionCount(1); } /** * @param string $line * @param string $message * * @return string '+', '-', '@', ' ' or '\' */ private function unifiedDiffAssertLinePrefix(string $line, string $message): string { $this->unifiedDiffAssertStrLength($line, 2, $message); // 2: line type indicator ('+', '-', ' ' or '\') and a line break $firstChar = $line[0]; if ('+' === $firstChar || '-' === $firstChar || '@' === $firstChar || ' ' === $firstChar) { return $firstChar; } if ("\\ No newline at end of file\n" === $line) { return '\\'; } throw new \UnexpectedValueException(\sprintf('Expected line to start with \'@\', \'-\' or \'+\', got "%s". %s', $line, $message)); } private function unifiedDiffAssertStrLength(string $line, int $min, string $message): void { $length = \strlen($line); if ($length < $min) { throw new \UnexpectedValueException(\sprintf('Expected string length of minimal %d, got %d. %s', $min, $length, $message)); } } /** * Assert valid unified diff header line * * Samples: * - "+++ from1.txt\t2017-08-24 19:51:29.383985722 +0200" * - "+++ from1.txt" * * @param string $line * @param string $start * @param string $message */ private function unifiedDiffAssertHeaderLine(string $line, string $start, string $message): void { if (0 !== \strpos($line, $start)) { throw new \UnexpectedValueException(\sprintf('Expected header line to start with "%s", got "%s". %s', $start . ' ', $line, $message)); } // sample "+++ from1.txt\t2017-08-24 19:51:29.383985722 +0200\n" $match = \preg_match( "/^([^\t]*)(?:[\t]([\\S].*[\\S]))?\n$/", \substr($line, 4), // 4 === string length of "+++ " / "--- " $matches ); if (1 !== $match) { throw new \UnexpectedValueException(\sprintf('Header line does not match expected pattern, got "%s". %s', $line, $message)); } // $file = $matches[1]; if (\count($matches) > 2) { $this->unifiedDiffAssertHeaderDate($matches[2], $message); } } private function unifiedDiffAssertHeaderDate(string $date, string $message): void { // sample "2017-08-24 19:51:29.383985722 +0200" $match = \preg_match( '/^([\d]{4})-([01]?[\d])-([0123]?[\d])(:? [\d]{1,2}:[\d]{1,2}(?::[\d]{1,2}(:?\.[\d]+)?)?(?: ([\+\-][\d]{4}))?)?$/', $date, $matches ); if (1 !== $match || ($matchesCount = \count($matches)) < 4) { throw new \UnexpectedValueException(\sprintf('Date of header line does not match expected pattern, got "%s". %s', $date, $message)); } // [$full, $year, $month, $day, $time] = $matches; } /** * @param string $line * @param string $message * * @return int[] */ private function unifiedDiffAssertHunkHeader(string $line, string $message): array { if (1 !== \preg_match('#^@@ -([\d]+)((?:,[\d]+)?) \+([\d]+)((?:,[\d]+)?) @@\n$#', $line, $matches)) { throw new \UnexpectedValueException( \sprintf( 'Hunk header line does not match expected pattern, got "%s". %s', $line, $message ) ); } return [ (int) $matches[1], empty($matches[2]) ? 1 : (int) \substr($matches[2], 1), (int) $matches[3], empty($matches[4]) ? 1 : (int) \substr($matches[4], 1), ]; } } PK! /Utils/UnifiedDiffAssertTraitIntegrationTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Diff\Utils; use PHPUnit\Framework\TestCase; use Symfony\Component\Process\Process; /** * @requires OS Linux * * @coversNothing */ final class UnifiedDiffAssertTraitIntegrationTest extends TestCase { use UnifiedDiffAssertTrait; private $filePatch; protected function setUp(): void { $this->filePatch = __DIR__ . '/../fixtures/out/patch.txt'; $this->cleanUpTempFiles(); } protected function tearDown(): void { $this->cleanUpTempFiles(); } /** * @param string $fileFrom * @param string $fileTo * * @dataProvider provideFilePairsCases */ public function testValidPatches(string $fileFrom, string $fileTo): void { $command = \sprintf( 'diff -u %s %s > %s', \escapeshellarg(\realpath($fileFrom)), \escapeshellarg(\realpath($fileTo)), \escapeshellarg($this->filePatch) ); $p = new Process($command); $p->run(); $exitCode = $p->getExitCode(); if (0 === $exitCode) { // odd case when two files have the same content. Test after executing as it is more efficient than to read the files and check the contents every time. $this->addToAssertionCount(1); return; } $this->assertSame( 1, // means `diff` found a diff between the files we gave it $exitCode, \sprintf( "Command exec. was not successful:\n\"%s\"\nOutput:\n\"%s\"\nStdErr:\n\"%s\"\nExit code %d.\n", $command, $p->getOutput(), $p->getErrorOutput(), $p->getExitCode() ) ); $this->assertValidUnifiedDiffFormat(FileUtils::getFileContent($this->filePatch)); } /** * @return array> */ public function provideFilePairsCases(): array { $cases = []; // created cases based on dedicated fixtures $dir = \realpath(__DIR__ . '/../fixtures/UnifiedDiffAssertTraitIntegrationTest'); $dirLength = \strlen($dir); for ($i = 1;; ++$i) { $fromFile = \sprintf('%s/%d_a.txt', $dir, $i); $toFile = \sprintf('%s/%d_b.txt', $dir, $i); if (!\file_exists($fromFile)) { break; } $this->assertFileExists($toFile); $cases[\sprintf("Diff file:\n\"%s\"\nvs.\n\"%s\"\n", \substr(\realpath($fromFile), $dirLength), \substr(\realpath($toFile), $dirLength))] = [$fromFile, $toFile]; } // create cases based on PHP files within the vendor directory for integration testing $dir = \realpath(__DIR__ . '/../../vendor'); $dirLength = \strlen($dir); $fileIterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dir, \RecursiveDirectoryIterator::SKIP_DOTS)); $fromFile = __FILE__; /** @var \SplFileInfo $file */ foreach ($fileIterator as $file) { if ('php' !== $file->getExtension()) { continue; } $toFile = $file->getPathname(); $cases[\sprintf("Diff file:\n\"%s\"\nvs.\n\"%s\"\n", \substr(\realpath($fromFile), $dirLength), \substr(\realpath($toFile), $dirLength))] = [$fromFile, $toFile]; $fromFile = $toFile; } return $cases; } private function cleanUpTempFiles(): void { @\unlink($this->filePatch); } } PK!?澚^^(Exception/ConfigurationExceptionTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Diff; use PHPUnit\Framework\TestCase; /** * @covers SebastianBergmann\Diff\ConfigurationException */ final class ConfigurationExceptionTest extends TestCase { public function testConstructWithDefaults(): void { $e = new ConfigurationException('test', 'A', 'B'); $this->assertSame(0, $e->getCode()); $this->assertNull($e->getPrevious()); $this->assertSame('Option "test" must be A, got "string#B".', $e->getMessage()); } public function testConstruct(): void { $e = new ConfigurationException( 'test', 'integer', new \SplFileInfo(__FILE__), 789, new \BadMethodCallException(__METHOD__) ); $this->assertSame('Option "test" must be integer, got "SplFileInfo".', $e->getMessage()); } } PK!7,8*Exception/InvalidArgumentExceptionTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Diff; use PHPUnit\Framework\TestCase; /** * @covers SebastianBergmann\Diff\InvalidArgumentException */ final class InvalidArgumentExceptionTest extends TestCase { public function testInvalidArgumentException(): void { $previousException = new \LogicException(); $message = 'test'; $code = 123; $exception = new InvalidArgumentException($message, $code, $previousException); $this->assertInstanceOf(Exception::class, $exception); $this->assertSame($message, $exception->getMessage()); $this->assertSame($code, $exception->getCode()); $this->assertSame($previousException, $exception->getPrevious()); } } PK!x LongestCommonSubsequenceTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Diff; use PHPUnit\Framework\TestCase; /** * @coversNothing */ abstract class LongestCommonSubsequenceTest extends TestCase { /** * @var LongestCommonSubsequenceCalculator */ private $implementation; /** * @var string */ private $memoryLimit; /** * @var int[] */ private $stress_sizes = [1, 2, 3, 100, 500, 1000, 2000]; protected function setUp(): void { $this->memoryLimit = \ini_get('memory_limit'); \ini_set('memory_limit', '256M'); $this->implementation = $this->createImplementation(); } protected function tearDown(): void { \ini_set('memory_limit', $this->memoryLimit); } public function testBothEmpty(): void { $from = []; $to = []; $common = $this->implementation->calculate($from, $to); $this->assertSame([], $common); } public function testIsStrictComparison(): void { $from = [ false, 0, 0.0, '', null, [], true, 1, 1.0, 'foo', ['foo', 'bar'], ['foo' => 'bar'], ]; $to = $from; $common = $this->implementation->calculate($from, $to); $this->assertSame($from, $common); $to = [ false, false, false, false, false, false, true, true, true, true, true, true, ]; $expected = [ false, true, ]; $common = $this->implementation->calculate($from, $to); $this->assertSame($expected, $common); } public function testEqualSequences(): void { foreach ($this->stress_sizes as $size) { $range = \range(1, $size); $from = $range; $to = $range; $common = $this->implementation->calculate($from, $to); $this->assertSame($range, $common); } } public function testDistinctSequences(): void { $from = ['A']; $to = ['B']; $common = $this->implementation->calculate($from, $to); $this->assertSame([], $common); $from = ['A', 'B', 'C']; $to = ['D', 'E', 'F']; $common = $this->implementation->calculate($from, $to); $this->assertSame([], $common); foreach ($this->stress_sizes as $size) { $from = \range(1, $size); $to = \range($size + 1, $size * 2); $common = $this->implementation->calculate($from, $to); $this->assertSame([], $common); } } public function testCommonSubsequence(): void { $from = ['A', 'C', 'E', 'F', 'G']; $to = ['A', 'B', 'D', 'E', 'H']; $expected = ['A', 'E']; $common = $this->implementation->calculate($from, $to); $this->assertSame($expected, $common); $from = ['A', 'C', 'E', 'F', 'G']; $to = ['B', 'C', 'D', 'E', 'F', 'H']; $expected = ['C', 'E', 'F']; $common = $this->implementation->calculate($from, $to); $this->assertSame($expected, $common); foreach ($this->stress_sizes as $size) { $from = $size < 2 ? [1] : \range(1, $size + 1, 2); $to = $size < 3 ? [1] : \range(1, $size + 1, 3); $expected = $size < 6 ? [1] : \range(1, $size + 1, 6); $common = $this->implementation->calculate($from, $to); $this->assertSame($expected, $common); } } public function testSingleElementSubsequenceAtStart(): void { foreach ($this->stress_sizes as $size) { $from = \range(1, $size); $to = \array_slice($from, 0, 1); $common = $this->implementation->calculate($from, $to); $this->assertSame($to, $common); } } public function testSingleElementSubsequenceAtMiddle(): void { foreach ($this->stress_sizes as $size) { $from = \range(1, $size); $to = \array_slice($from, (int) ($size / 2), 1); $common = $this->implementation->calculate($from, $to); $this->assertSame($to, $common); } } public function testSingleElementSubsequenceAtEnd(): void { foreach ($this->stress_sizes as $size) { $from = \range(1, $size); $to = \array_slice($from, $size - 1, 1); $common = $this->implementation->calculate($from, $to); $this->assertSame($to, $common); } } public function testReversedSequences(): void { $from = ['A', 'B']; $to = ['B', 'A']; $expected = ['A']; $common = $this->implementation->calculate($from, $to); $this->assertSame($expected, $common); foreach ($this->stress_sizes as $size) { $from = \range(1, $size); $to = \array_reverse($from); $common = $this->implementation->calculate($from, $to); $this->assertSame([1], $common); } } public function testStrictTypeCalculate(): void { $diff = $this->implementation->calculate(['5'], ['05']); $this->assertIsArray($diff); $this->assertCount(0, $diff); } /** * @return LongestCommonSubsequenceCalculator */ abstract protected function createImplementation(): LongestCommonSubsequenceCalculator; } PK!2otA/Output/UnifiedDiffOutputBuilderDataProvider.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Diff\Output; final class UnifiedDiffOutputBuilderDataProvider { public static function provideDiffWithLineNumbers(): array { return [ 'diff line 1 non_patch_compat' => [ '--- Original +++ New @@ -1 +1 @@ -AA +BA ', 'AA', 'BA', ], 'diff line +1 non_patch_compat' => [ '--- Original +++ New @@ -1 +1,2 @@ -AZ + +B ', 'AZ', "\nB", ], 'diff line -1 non_patch_compat' => [ '--- Original +++ New @@ -1,2 +1 @@ - -AF +B ', "\nAF", 'B', ], 'II non_patch_compat' => [ '--- Original +++ New @@ -1,4 +1,2 @@ - - A 1 ', "\n\nA\n1", "A\n1", ], 'diff last line II - no trailing linebreak non_patch_compat' => [ '--- Original +++ New @@ -5,4 +5,4 @@ ' . ' ' . ' ' . ' -E +B ', "A\n\n\n\n\n\n\nE", "A\n\n\n\n\n\n\nB", ], [ "--- Original\n+++ New\n@@ -1,2 +1 @@\n \n-\n", "\n\n", "\n", ], 'diff line endings non_patch_compat' => [ "--- Original\n+++ New\n@@ -1 +1 @@\n #Warning: Strings contain different line endings!\n- [ '--- Original +++ New ', "AT\n", "AT\n", ], [ '--- Original +++ New @@ -1,4 +1,4 @@ -b +a ' . ' ' . ' ' . ' ', "b\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "a\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", ], 'diff line @1' => [ '--- Original +++ New @@ -1,2 +1,2 @@ ' . ' -AG +B ', "\nAG\n", "\nB\n", ], 'same multiple lines' => [ '--- Original +++ New @@ -1,4 +1,4 @@ ' . ' ' . ' -V +B C213 ', "\n\nV\nC213", "\n\nB\nC213", ], 'diff last line I' => [ '--- Original +++ New @@ -5,4 +5,4 @@ ' . ' ' . ' ' . ' -E +B ', "A\n\n\n\n\n\n\nE\n", "A\n\n\n\n\n\n\nB\n", ], 'diff line middle' => [ '--- Original +++ New @@ -5,7 +5,7 @@ ' . ' ' . ' ' . ' -X +Z ' . ' ' . ' ' . ' ', "A\n\n\n\n\n\n\nX\n\n\n\n\n\n\nAY", "A\n\n\n\n\n\n\nZ\n\n\n\n\n\n\nAY", ], 'diff last line III' => [ '--- Original +++ New @@ -12,4 +12,4 @@ ' . ' ' . ' ' . ' -A +B ', "A\n\n\n\n\n\n\nA\n\n\n\n\n\n\nA\n", "A\n\n\n\n\n\n\nA\n\n\n\n\n\n\nB\n", ], [ '--- Original +++ New @@ -1,8 +1,8 @@ A -B +B1 D E EE F -G +G1 H ', "A\nB\nD\nE\nEE\nF\nG\nH", "A\nB1\nD\nE\nEE\nF\nG1\nH", ], [ '--- Original +++ New @@ -1,4 +1,5 @@ Z + a b c @@ -7,5 +8,5 @@ f g h -i +x j ', 'Z a b c d e f g h i j ', 'Z a b c d e f g h x j ', ], [ '--- Original +++ New @@ -1,7 +1,5 @@ - -a +b A -X - +Y ' . ' A ', "\na\nA\nX\n\n\nA\n", "b\nA\nY\n\nA\n", ], [ <<Output/Integration/UnifiedDiffOutputBuilderIntegrationTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Diff\Output; use PHPUnit\Framework\TestCase; use SebastianBergmann\Diff\Utils\UnifiedDiffAssertTrait; use Symfony\Component\Process\Process; /** * @covers SebastianBergmann\Diff\Output\UnifiedDiffOutputBuilder * * @uses SebastianBergmann\Diff\Differ * @uses SebastianBergmann\Diff\TimeEfficientLongestCommonSubsequenceCalculator * * @requires OS Linux */ final class UnifiedDiffOutputBuilderIntegrationTest extends TestCase { use UnifiedDiffAssertTrait; private $dir; private $fileFrom; private $filePatch; protected function setUp(): void { $this->dir = \realpath(__DIR__ . '/../../fixtures/out/') . '/'; $this->fileFrom = $this->dir . 'from.txt'; $this->filePatch = $this->dir . 'patch.txt'; $this->cleanUpTempFiles(); } protected function tearDown(): void { $this->cleanUpTempFiles(); } /** * @dataProvider provideDiffWithLineNumbers * * @param mixed $expected * @param mixed $from * @param mixed $to */ public function testDiffWithLineNumbersPath($expected, $from, $to): void { $this->doIntegrationTestPatch($expected, $from, $to); } /** * @dataProvider provideDiffWithLineNumbers * * @param mixed $expected * @param mixed $from * @param mixed $to */ public function testDiffWithLineNumbersGitApply($expected, $from, $to): void { $this->doIntegrationTestGitApply($expected, $from, $to); } public function provideDiffWithLineNumbers() { return \array_filter( UnifiedDiffOutputBuilderDataProvider::provideDiffWithLineNumbers(), static function ($key) { return !\is_string($key) || false === \strpos($key, 'non_patch_compat'); }, ARRAY_FILTER_USE_KEY ); } private function doIntegrationTestPatch(string $diff, string $from, string $to): void { $this->assertNotSame('', $diff); $this->assertValidUnifiedDiffFormat($diff); $diff = self::setDiffFileHeader($diff, $this->fileFrom); $this->assertNotFalse(\file_put_contents($this->fileFrom, $from)); $this->assertNotFalse(\file_put_contents($this->filePatch, $diff)); $command = \sprintf( 'patch -u --verbose --posix %s < %s', // --posix \escapeshellarg($this->fileFrom), \escapeshellarg($this->filePatch) ); $p = new Process($command); $p->run(); $this->assertProcessSuccessful($p); $this->assertStringEqualsFile( $this->fileFrom, $to, \sprintf('Patch command "%s".', $command) ); } private function doIntegrationTestGitApply(string $diff, string $from, string $to): void { $this->assertNotSame('', $diff); $this->assertValidUnifiedDiffFormat($diff); $diff = self::setDiffFileHeader($diff, $this->fileFrom); $this->assertNotFalse(\file_put_contents($this->fileFrom, $from)); $this->assertNotFalse(\file_put_contents($this->filePatch, $diff)); $command = \sprintf( 'git --git-dir %s apply --check -v --unsafe-paths --ignore-whitespace %s', \escapeshellarg($this->dir), \escapeshellarg($this->filePatch) ); $p = new Process($command); $p->run(); $this->assertProcessSuccessful($p); } private function assertProcessSuccessful(Process $p): void { $this->assertTrue( $p->isSuccessful(), \sprintf( "Command exec. was not successful:\n\"%s\"\nOutput:\n\"%s\"\nStdErr:\n\"%s\"\nExit code %d.\n", $p->getCommandLine(), $p->getOutput(), $p->getErrorOutput(), $p->getExitCode() ) ); } private function cleanUpTempFiles(): void { @\unlink($this->fileFrom . '.orig'); @\unlink($this->fileFrom); @\unlink($this->filePatch); } private static function setDiffFileHeader(string $diff, string $file): string { $diffLines = \preg_split('/(.*\R)/', $diff, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); $diffLines[0] = \preg_replace('#^\-\-\- .*#', '--- /' . $file, $diffLines[0], 1); $diffLines[1] = \preg_replace('#^\+\+\+ .*#', '+++ /' . $file, $diffLines[1], 1); return \implode('', $diffLines); } } PK!ܫ<'<'DOutput/Integration/StrictUnifiedDiffOutputBuilderIntegrationTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Diff\Output; use PHPUnit\Framework\TestCase; use SebastianBergmann\Diff\Differ; use SebastianBergmann\Diff\Utils\FileUtils; use SebastianBergmann\Diff\Utils\UnifiedDiffAssertTrait; use Symfony\Component\Process\Process; /** * @covers SebastianBergmann\Diff\Output\StrictUnifiedDiffOutputBuilder * * @uses SebastianBergmann\Diff\Differ * @uses SebastianBergmann\Diff\TimeEfficientLongestCommonSubsequenceCalculator * * @requires OS Linux */ final class StrictUnifiedDiffOutputBuilderIntegrationTest extends TestCase { use UnifiedDiffAssertTrait; private $dir; private $fileFrom; private $fileTo; private $filePatch; protected function setUp(): void { $this->dir = \realpath(__DIR__ . '/../../fixtures/out') . '/'; $this->fileFrom = $this->dir . 'from.txt'; $this->fileTo = $this->dir . 'to.txt'; $this->filePatch = $this->dir . 'diff.patch'; if (!\is_dir($this->dir)) { throw new \RuntimeException('Integration test working directory not found.'); } $this->cleanUpTempFiles(); } protected function tearDown(): void { $this->cleanUpTempFiles(); } /** * Integration test * * - get a file pair * - create a `diff` between the files * - test applying the diff using `git apply` * - test applying the diff using `patch` * * @param string $fileFrom * @param string $fileTo * * @dataProvider provideFilePairs */ public function testIntegrationUsingPHPFileInVendorGitApply(string $fileFrom, string $fileTo): void { $from = FileUtils::getFileContent($fileFrom); $to = FileUtils::getFileContent($fileTo); $diff = (new Differ(new StrictUnifiedDiffOutputBuilder(['fromFile' => 'Original', 'toFile' => 'New'])))->diff($from, $to); if ('' === $diff && $from === $to) { // odd case: test after executing as it is more efficient than to read the files and check the contents every time $this->addToAssertionCount(1); return; } $this->doIntegrationTestGitApply($diff, $from, $to); } /** * Integration test * * - get a file pair * - create a `diff` between the files * - test applying the diff using `git apply` * - test applying the diff using `patch` * * @param string $fileFrom * @param string $fileTo * * @dataProvider provideFilePairs */ public function testIntegrationUsingPHPFileInVendorPatch(string $fileFrom, string $fileTo): void { $from = FileUtils::getFileContent($fileFrom); $to = FileUtils::getFileContent($fileTo); $diff = (new Differ(new StrictUnifiedDiffOutputBuilder(['fromFile' => 'Original', 'toFile' => 'New'])))->diff($from, $to); if ('' === $diff && $from === $to) { // odd case: test after executing as it is more efficient than to read the files and check the contents every time $this->addToAssertionCount(1); return; } $this->doIntegrationTestPatch($diff, $from, $to); } /** * @param string $expected * @param string $from * @param string $to * * @dataProvider provideOutputBuildingCases * @dataProvider provideSample * @dataProvider provideBasicDiffGeneration */ public function testIntegrationOfUnitTestCasesGitApply(string $expected, string $from, string $to): void { $this->doIntegrationTestGitApply($expected, $from, $to); } /** * @param string $expected * @param string $from * @param string $to * * @dataProvider provideOutputBuildingCases * @dataProvider provideSample * @dataProvider provideBasicDiffGeneration */ public function testIntegrationOfUnitTestCasesPatch(string $expected, string $from, string $to): void { $this->doIntegrationTestPatch($expected, $from, $to); } public function provideOutputBuildingCases(): array { return StrictUnifiedDiffOutputBuilderDataProvider::provideOutputBuildingCases(); } public function provideSample(): array { return StrictUnifiedDiffOutputBuilderDataProvider::provideSample(); } public function provideBasicDiffGeneration(): array { return StrictUnifiedDiffOutputBuilderDataProvider::provideBasicDiffGeneration(); } public function provideFilePairs(): array { $cases = []; $fromFile = __FILE__; $vendorDir = \realpath(__DIR__ . '/../../../vendor'); $fileIterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($vendorDir, \RecursiveDirectoryIterator::SKIP_DOTS)); /** @var \SplFileInfo $file */ foreach ($fileIterator as $file) { if ('php' !== $file->getExtension()) { continue; } $toFile = $file->getPathname(); $cases[\sprintf("Diff file:\n\"%s\"\nvs.\n\"%s\"\n", \realpath($fromFile), \realpath($toFile))] = [$fromFile, $toFile]; $fromFile = $toFile; } return $cases; } /** * Compare diff create by builder and against one create by `diff` command. * * @param string $diff * @param string $from * @param string $to * * @dataProvider provideBasicDiffGeneration */ public function testIntegrationDiffOutputBuilderVersusDiffCommand(string $diff, string $from, string $to): void { $this->assertNotSame('', $diff); $this->assertValidUnifiedDiffFormat($diff); $this->assertNotFalse(\file_put_contents($this->fileFrom, $from)); $this->assertNotFalse(\file_put_contents($this->fileTo, $to)); $p = new Process(\sprintf('diff -u %s %s', \escapeshellarg($this->fileFrom), \escapeshellarg($this->fileTo))); $p->run(); $this->assertSame(1, $p->getExitCode()); // note: Process assumes exit code 0 for `isSuccessful`, however `diff` uses the exit code `1` for success with diff $output = $p->getOutput(); $diffLines = \preg_split('/(.*\R)/', $diff, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); $diffLines[0] = \preg_replace('#^\-\-\- .*#', '--- /' . $this->fileFrom, $diffLines[0], 1); $diffLines[1] = \preg_replace('#^\+\+\+ .*#', '+++ /' . $this->fileFrom, $diffLines[1], 1); $diff = \implode('', $diffLines); $outputLines = \preg_split('/(.*\R)/', $output, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); $outputLines[0] = \preg_replace('#^\-\-\- .*#', '--- /' . $this->fileFrom, $outputLines[0], 1); $outputLines[1] = \preg_replace('#^\+\+\+ .*#', '+++ /' . $this->fileFrom, $outputLines[1], 1); $output = \implode('', $outputLines); $this->assertSame($diff, $output); } private function doIntegrationTestGitApply(string $diff, string $from, string $to): void { $this->assertNotSame('', $diff); $this->assertValidUnifiedDiffFormat($diff); $diff = self::setDiffFileHeader($diff, $this->fileFrom); $this->assertNotFalse(\file_put_contents($this->fileFrom, $from)); $this->assertNotFalse(\file_put_contents($this->filePatch, $diff)); $p = new Process(\sprintf( 'git --git-dir %s apply --check -v --unsafe-paths --ignore-whitespace %s', \escapeshellarg($this->dir), \escapeshellarg($this->filePatch) )); $p->run(); $this->assertProcessSuccessful($p); } private function doIntegrationTestPatch(string $diff, string $from, string $to): void { $this->assertNotSame('', $diff); $this->assertValidUnifiedDiffFormat($diff); $diff = self::setDiffFileHeader($diff, $this->fileFrom); $this->assertNotFalse(\file_put_contents($this->fileFrom, $from)); $this->assertNotFalse(\file_put_contents($this->filePatch, $diff)); $command = \sprintf( 'patch -u --verbose --posix %s < %s', \escapeshellarg($this->fileFrom), \escapeshellarg($this->filePatch) ); $p = new Process($command); $p->run(); $this->assertProcessSuccessful($p); $this->assertStringEqualsFile( $this->fileFrom, $to, \sprintf('Patch command "%s".', $command) ); } private function assertProcessSuccessful(Process $p): void { $this->assertTrue( $p->isSuccessful(), \sprintf( "Command exec. was not successful:\n\"%s\"\nOutput:\n\"%s\"\nStdErr:\n\"%s\"\nExit code %d.\n", $p->getCommandLine(), $p->getOutput(), $p->getErrorOutput(), $p->getExitCode() ) ); } private function cleanUpTempFiles(): void { @\unlink($this->fileFrom . '.orig'); @\unlink($this->fileFrom . '.rej'); @\unlink($this->fileFrom); @\unlink($this->fileTo); @\unlink($this->filePatch); } private static function setDiffFileHeader(string $diff, string $file): string { $diffLines = \preg_split('/(.*\R)/', $diff, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); $diffLines[0] = \preg_replace('#^\-\-\- .*#', '--- /' . $file, $diffLines[0], 1); $diffLines[1] = \preg_replace('#^\+\+\+ .*#', '+++ /' . $file, $diffLines[1], 1); return \implode('', $diffLines); } } PK!+VDVD-Output/StrictUnifiedDiffOutputBuilderTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Diff\Output; use PHPUnit\Framework\TestCase; use SebastianBergmann\Diff\ConfigurationException; use SebastianBergmann\Diff\Differ; use SebastianBergmann\Diff\Utils\UnifiedDiffAssertTrait; /** * @covers SebastianBergmann\Diff\Output\StrictUnifiedDiffOutputBuilder * * @uses SebastianBergmann\Diff\Differ */ final class StrictUnifiedDiffOutputBuilderTest extends TestCase { use UnifiedDiffAssertTrait; /** * @param string $expected * @param string $from * @param string $to * @param array $options * * @dataProvider provideOutputBuildingCases */ public function testOutputBuilding(string $expected, string $from, string $to, array $options): void { $diff = $this->getDiffer($options)->diff($from, $to); $this->assertValidDiffFormat($diff); $this->assertSame($expected, $diff); } /** * @param string $expected * @param string $from * @param string $to * @param array $options * * @dataProvider provideSample */ public function testSample(string $expected, string $from, string $to, array $options): void { $diff = $this->getDiffer($options)->diff($from, $to); $this->assertValidDiffFormat($diff); $this->assertSame($expected, $diff); } /** * {@inheritdoc} */ public function assertValidDiffFormat(string $diff): void { $this->assertValidUnifiedDiffFormat($diff); } /** * {@inheritdoc} */ public function provideOutputBuildingCases(): array { return StrictUnifiedDiffOutputBuilderDataProvider::provideOutputBuildingCases(); } /** * {@inheritdoc} */ public function provideSample(): array { return StrictUnifiedDiffOutputBuilderDataProvider::provideSample(); } /** * @param string $expected * @param string $from * @param string $to * * @dataProvider provideBasicDiffGeneration */ public function testBasicDiffGeneration(string $expected, string $from, string $to): void { $diff = $this->getDiffer([ 'fromFile' => 'input.txt', 'toFile' => 'output.txt', ])->diff($from, $to); $this->assertValidDiffFormat($diff); $this->assertSame($expected, $diff); } public function provideBasicDiffGeneration(): array { return StrictUnifiedDiffOutputBuilderDataProvider::provideBasicDiffGeneration(); } /** * @param string $expected * @param string $from * @param string $to * @param array $config * * @dataProvider provideConfiguredDiffGeneration */ public function testConfiguredDiffGeneration(string $expected, string $from, string $to, array $config = []): void { $diff = $this->getDiffer(\array_merge([ 'fromFile' => 'input.txt', 'toFile' => 'output.txt', ], $config))->diff($from, $to); $this->assertValidDiffFormat($diff); $this->assertSame($expected, $diff); } public function provideConfiguredDiffGeneration(): array { return [ [ '--- input.txt +++ output.txt @@ -1 +1 @@ -a \ No newline at end of file +b \ No newline at end of file ', 'a', 'b', ], [ '', "1\n2", "1\n2", ], [ '', "1\n", "1\n", ], [ '--- input.txt +++ output.txt @@ -4 +4 @@ -X +4 ', "1\n2\n3\nX\n5\n6\n7\n8\n9\n0\n", "1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n", [ 'contextLines' => 0, ], ], [ '--- input.txt +++ output.txt @@ -3,3 +3,3 @@ 3 -X +4 5 ', "1\n2\n3\nX\n5\n6\n7\n8\n9\n0\n", "1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n", [ 'contextLines' => 1, ], ], [ '--- input.txt +++ output.txt @@ -1,10 +1,10 @@ 1 2 3 -X +4 5 6 7 8 9 0 ', "1\n2\n3\nX\n5\n6\n7\n8\n9\n0\n", "1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n", [ 'contextLines' => 999, ], ], [ '--- input.txt +++ output.txt @@ -1,0 +1,2 @@ + +A ', '', "\nA\n", ], [ '--- input.txt +++ output.txt @@ -1,2 +1,0 @@ - -A ', "\nA\n", '', ], [ '--- input.txt +++ output.txt @@ -1,5 +1,5 @@ 1 -X +2 3 -Y +4 5 @@ -8,3 +8,3 @@ 8 -X +9 0 ', "1\nX\n3\nY\n5\n6\n7\n8\nX\n0\n", "1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n", [ 'commonLineThreshold' => 2, 'contextLines' => 1, ], ], [ '--- input.txt +++ output.txt @@ -2 +2 @@ -X +2 @@ -4 +4 @@ -Y +4 @@ -9 +9 @@ -X +9 ', "1\nX\n3\nY\n5\n6\n7\n8\nX\n0\n", "1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n", [ 'commonLineThreshold' => 1, 'contextLines' => 0, ], ], ]; } public function testReUseBuilder(): void { $differ = $this->getDiffer([ 'fromFile' => 'input.txt', 'toFile' => 'output.txt', ]); $diff = $differ->diff("A\nB\n", "A\nX\n"); $this->assertSame( '--- input.txt +++ output.txt @@ -1,2 +1,2 @@ A -B +X ', $diff ); $diff = $differ->diff("A\n", "A\n"); $this->assertSame( '', $diff ); } public function testEmptyDiff(): void { $builder = new StrictUnifiedDiffOutputBuilder([ 'fromFile' => 'input.txt', 'toFile' => 'output.txt', ]); $this->assertSame( '', $builder->getDiff([]) ); } /** * @param array $options * @param string $message * * @dataProvider provideInvalidConfiguration */ public function testInvalidConfiguration(array $options, string $message): void { $this->expectException(ConfigurationException::class); $this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote($message, '#'))); new StrictUnifiedDiffOutputBuilder($options); } public function provideInvalidConfiguration(): array { $time = \time(); return [ [ ['collapseRanges' => 1], 'Option "collapseRanges" must be a bool, got "integer#1".', ], [ ['contextLines' => 'a'], 'Option "contextLines" must be an int >= 0, got "string#a".', ], [ ['commonLineThreshold' => -2], 'Option "commonLineThreshold" must be an int > 0, got "integer#-2".', ], [ ['commonLineThreshold' => 0], 'Option "commonLineThreshold" must be an int > 0, got "integer#0".', ], [ ['fromFile' => new \SplFileInfo(__FILE__)], 'Option "fromFile" must be a string, got "SplFileInfo".', ], [ ['fromFile' => null], 'Option "fromFile" must be a string, got "".', ], [ [ 'fromFile' => __FILE__, 'toFile' => 1, ], 'Option "toFile" must be a string, got "integer#1".', ], [ [ 'fromFile' => __FILE__, 'toFile' => __FILE__, 'toFileDate' => $time, ], 'Option "toFileDate" must be a string or , got "integer#' . $time . '".', ], [ [], 'Option "fromFile" must be a string, got "".', ], ]; } /** * @param string $expected * @param string $from * @param string $to * @param int $threshold * * @dataProvider provideCommonLineThresholdCases */ public function testCommonLineThreshold(string $expected, string $from, string $to, int $threshold): void { $diff = $this->getDiffer([ 'fromFile' => 'input.txt', 'toFile' => 'output.txt', 'commonLineThreshold' => $threshold, 'contextLines' => 0, ])->diff($from, $to); $this->assertValidDiffFormat($diff); $this->assertSame($expected, $diff); } public function provideCommonLineThresholdCases(): array { return [ [ '--- input.txt +++ output.txt @@ -2,3 +2,3 @@ -X +B C12 -Y +D @@ -7 +7 @@ -X +Z ', "A\nX\nC12\nY\nA\nA\nX\n", "A\nB\nC12\nD\nA\nA\nZ\n", 2, ], [ '--- input.txt +++ output.txt @@ -2 +2 @@ -X +B @@ -4 +4 @@ -Y +D ', "A\nX\nV\nY\n", "A\nB\nV\nD\n", 1, ], ]; } /** * @param string $expected * @param string $from * @param string $to * @param int $contextLines * @param int $commonLineThreshold * * @dataProvider provideContextLineConfigurationCases */ public function testContextLineConfiguration(string $expected, string $from, string $to, int $contextLines, int $commonLineThreshold = 6): void { $diff = $this->getDiffer([ 'fromFile' => 'input.txt', 'toFile' => 'output.txt', 'contextLines' => $contextLines, 'commonLineThreshold' => $commonLineThreshold, ])->diff($from, $to); $this->assertValidDiffFormat($diff); $this->assertSame($expected, $diff); } public function provideContextLineConfigurationCases(): array { $from = "A\nB\nC\nD\nE\nF\nX\nG\nH\nI\nJ\nK\nL\nM\n"; $to = "A\nB\nC\nD\nE\nF\nY\nG\nH\nI\nJ\nK\nL\nM\n"; return [ 'EOF 0' => [ "--- input.txt\n+++ output.txt\n@@ -3 +3 @@ -X \\ No newline at end of file +Y \\ No newline at end of file ", "A\nB\nX", "A\nB\nY", 0, ], 'EOF 1' => [ "--- input.txt\n+++ output.txt\n@@ -2,2 +2,2 @@ B -X \\ No newline at end of file +Y \\ No newline at end of file ", "A\nB\nX", "A\nB\nY", 1, ], 'EOF 2' => [ "--- input.txt\n+++ output.txt\n@@ -1,3 +1,3 @@ A B -X \\ No newline at end of file +Y \\ No newline at end of file ", "A\nB\nX", "A\nB\nY", 2, ], 'EOF 200' => [ "--- input.txt\n+++ output.txt\n@@ -1,3 +1,3 @@ A B -X \\ No newline at end of file +Y \\ No newline at end of file ", "A\nB\nX", "A\nB\nY", 200, ], 'n/a 0' => [ "--- input.txt\n+++ output.txt\n@@ -7 +7 @@\n-X\n+Y\n", $from, $to, 0, ], 'G' => [ "--- input.txt\n+++ output.txt\n@@ -6,3 +6,3 @@\n F\n-X\n+Y\n G\n", $from, $to, 1, ], 'H' => [ "--- input.txt\n+++ output.txt\n@@ -5,5 +5,5 @@\n E\n F\n-X\n+Y\n G\n H\n", $from, $to, 2, ], 'I' => [ "--- input.txt\n+++ output.txt\n@@ -4,7 +4,7 @@\n D\n E\n F\n-X\n+Y\n G\n H\n I\n", $from, $to, 3, ], 'J' => [ "--- input.txt\n+++ output.txt\n@@ -3,9 +3,9 @@\n C\n D\n E\n F\n-X\n+Y\n G\n H\n I\n J\n", $from, $to, 4, ], 'K' => [ "--- input.txt\n+++ output.txt\n@@ -2,11 +2,11 @@\n B\n C\n D\n E\n F\n-X\n+Y\n G\n H\n I\n J\n K\n", $from, $to, 5, ], 'L' => [ "--- input.txt\n+++ output.txt\n@@ -1,13 +1,13 @@\n A\n B\n C\n D\n E\n F\n-X\n+Y\n G\n H\n I\n J\n K\n L\n", $from, $to, 6, ], 'M' => [ "--- input.txt\n+++ output.txt\n@@ -1,14 +1,14 @@\n A\n B\n C\n D\n E\n F\n-X\n+Y\n G\n H\n I\n J\n K\n L\n M\n", $from, $to, 7, ], 'M no linebreak EOF .1' => [ "--- input.txt\n+++ output.txt\n@@ -1,14 +1,14 @@\n A\n B\n C\n D\n E\n F\n-X\n+Y\n G\n H\n I\n J\n K\n L\n-M\n+M\n\\ No newline at end of file\n", $from, \substr($to, 0, -1), 7, ], 'M no linebreak EOF .2' => [ "--- input.txt\n+++ output.txt\n@@ -1,14 +1,14 @@\n A\n B\n C\n D\n E\n F\n-X\n+Y\n G\n H\n I\n J\n K\n L\n-M\n\\ No newline at end of file\n+M\n", \substr($from, 0, -1), $to, 7, ], 'M no linebreak EOF .3' => [ "--- input.txt\n+++ output.txt\n@@ -1,14 +1,14 @@\n A\n B\n C\n D\n E\n F\n-X\n+Y\n G\n H\n I\n J\n K\n L\n M\n", \substr($from, 0, -1), \substr($to, 0, -1), 7, ], 'M no linebreak EOF .4' => [ "--- input.txt\n+++ output.txt\n@@ -1,14 +1,14 @@\n A\n B\n C\n D\n E\n F\n-X\n+Y\n G\n H\n I\n J\n K\n L\n M\n\\ No newline at end of file\n", \substr($from, 0, -1), \substr($to, 0, -1), 10000, 10000, ], 'M+1' => [ "--- input.txt\n+++ output.txt\n@@ -1,14 +1,14 @@\n A\n B\n C\n D\n E\n F\n-X\n+Y\n G\n H\n I\n J\n K\n L\n M\n", $from, $to, 8, ], 'M+100' => [ "--- input.txt\n+++ output.txt\n@@ -1,14 +1,14 @@\n A\n B\n C\n D\n E\n F\n-X\n+Y\n G\n H\n I\n J\n K\n L\n M\n", $from, $to, 107, ], '0 II' => [ "--- input.txt\n+++ output.txt\n@@ -12 +12 @@\n-X\n+Y\n", "A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nX\nM\n", "A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nY\nM\n", 0, 999, ], '0\' II' => [ "--- input.txt\n+++ output.txt\n@@ -12 +12 @@\n-X\n+Y\n", "A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nX\nM\nA\nA\nA\nA\nA\n", "A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nY\nM\nA\nA\nA\nA\nA\n", 0, 999, ], '0\'\' II' => [ "--- input.txt\n+++ output.txt\n@@ -12,2 +12,2 @@\n-X\n-M\n\\ No newline at end of file\n+Y\n+M\n", "A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nX\nM", "A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nY\nM\n", 0, ], '0\'\'\' II' => [ "--- input.txt\n+++ output.txt\n@@ -12,2 +12,2 @@\n-X\n-X1\n+Y\n+Y2\n", "A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nX\nX1\nM\nA\nA\nA\nA\nA\n", "A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nY\nY2\nM\nA\nA\nA\nA\nA\n", 0, 999, ], '1 II' => [ "--- input.txt\n+++ output.txt\n@@ -11,3 +11,3 @@\n K\n-X\n+Y\n M\n", "A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nX\nM\n", "A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nY\nM\n", 1, ], '5 II' => [ "--- input.txt\n+++ output.txt\n@@ -7,7 +7,7 @@\n G\n H\n I\n J\n K\n-X\n+Y\n M\n", "A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nX\nM\n", "A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nY\nM\n", 5, ], [ '--- input.txt +++ output.txt @@ -1,28 +1,28 @@ A -X +B V -Y +D 1 A 2 A 3 A 4 A 8 A 9 A 5 A A A A A A A A A A A ', "A\nX\nV\nY\n1\nA\n2\nA\n3\nA\n4\nA\n8\nA\n9\nA\n5\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\n", "A\nB\nV\nD\n1\nA\n2\nA\n3\nA\n4\nA\n8\nA\n9\nA\n5\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\n", 9999, 99999, ], ]; } /** * Returns a new instance of a Differ with a new instance of the class (DiffOutputBuilderInterface) under test. * * @param array $options * * @return Differ */ private function getDiffer(array $options = []): Differ { return new Differ(new StrictUnifiedDiffOutputBuilder($options)); } } PK!z6|dd$Output/DiffOnlyOutputBuilderTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Diff\Output; use PHPUnit\Framework\TestCase; use SebastianBergmann\Diff\Differ; /** * @covers SebastianBergmann\Diff\Output\DiffOnlyOutputBuilder * * @uses SebastianBergmann\Diff\Differ * @uses SebastianBergmann\Diff\TimeEfficientLongestCommonSubsequenceCalculator */ final class DiffOnlyOutputBuilderTest extends TestCase { /** * @param string $expected * @param string $from * @param string $to * @param string $header * * @dataProvider textForNoNonDiffLinesProvider */ public function testDiffDoNotShowNonDiffLines(string $expected, string $from, string $to, string $header = ''): void { $differ = new Differ(new DiffOnlyOutputBuilder($header)); $this->assertSame($expected, $differ->diff($from, $to)); } public function textForNoNonDiffLinesProvider(): array { return [ [ " #Warning: Strings contain different line endings!\n-A\r\n+B\n", "A\r\n", "B\n", ], [ "-A\n+B\n", "\nA", "\nB", ], [ '', 'a', 'a', ], [ "-A\n+C\n", "A\n\n\nB", "C\n\n\nB", ], [ "header\n", 'a', 'a', 'header', ], [ "header\n", 'a', 'a', "header\n", ], ]; } } PK!(& & 5Output/StrictUnifiedDiffOutputBuilderDataProvider.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Diff\Output; final class StrictUnifiedDiffOutputBuilderDataProvider { public static function provideOutputBuildingCases(): array { return [ [ '--- input.txt +++ output.txt @@ -1,3 +1,4 @@ +b ' . ' ' . ' ' . ' @@ -16,5 +17,4 @@ ' . ' ' . ' ' . ' - -B +A ', "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nB\n", "b\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nA\n", [ 'fromFile' => 'input.txt', 'toFile' => 'output.txt', ], ], [ '--- ' . __FILE__ . "\t2017-10-02 17:38:11.586413675 +0100 +++ output1.txt\t2017-10-03 12:09:43.086719482 +0100 @@ -1,1 +1,1 @@ -B +X ", "B\n", "X\n", [ 'fromFile' => __FILE__, 'fromFileDate' => '2017-10-02 17:38:11.586413675 +0100', 'toFile' => 'output1.txt', 'toFileDate' => '2017-10-03 12:09:43.086719482 +0100', 'collapseRanges' => false, ], ], [ '--- input.txt +++ output.txt @@ -1 +1 @@ -B +X ', "B\n", "X\n", [ 'fromFile' => 'input.txt', 'toFile' => 'output.txt', 'collapseRanges' => true, ], ], ]; } public static function provideSample(): array { return [ [ '--- input.txt +++ output.txt @@ -1,6 +1,6 @@ 1 2 3 -4 +X 5 6 ', "1\n2\n3\n4\n5\n6\n", "1\n2\n3\nX\n5\n6\n", [ 'fromFile' => 'input.txt', 'toFile' => 'output.txt', ], ], ]; } public static function provideBasicDiffGeneration(): array { return [ [ "--- input.txt +++ output.txt @@ -1,2 +1 @@ -A -B +A\rB ", "A\nB\n", "A\rB\n", ], [ "--- input.txt +++ output.txt @@ -1 +1 @@ - +\r \\ No newline at end of file ", "\n", "\r", ], [ "--- input.txt +++ output.txt @@ -1 +1 @@ -\r \\ No newline at end of file + ", "\r", "\n", ], [ '--- input.txt +++ output.txt @@ -1,3 +1,3 @@ X A -A +B ', "X\nA\nA\n", "X\nA\nB\n", ], [ '--- input.txt +++ output.txt @@ -1,3 +1,3 @@ X A -A \ No newline at end of file +B ', "X\nA\nA", "X\nA\nB\n", ], [ '--- input.txt +++ output.txt @@ -1,3 +1,3 @@ A A -A +B \ No newline at end of file ', "A\nA\nA\n", "A\nA\nB", ], [ '--- input.txt +++ output.txt @@ -1 +1 @@ -A \ No newline at end of file +B \ No newline at end of file ', 'A', 'B', ], ]; } } PK!zlV V 'Output/UnifiedDiffOutputBuilderTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Diff\Output; use PHPUnit\Framework\TestCase; use SebastianBergmann\Diff\Differ; /** * @covers SebastianBergmann\Diff\Output\UnifiedDiffOutputBuilder * * @uses SebastianBergmann\Diff\Differ * @uses SebastianBergmann\Diff\Output\AbstractChunkOutputBuilder * @uses SebastianBergmann\Diff\TimeEfficientLongestCommonSubsequenceCalculator */ final class UnifiedDiffOutputBuilderTest extends TestCase { /** * @param string $expected * @param string $from * @param string $to * @param string $header * * @dataProvider headerProvider */ public function testCustomHeaderCanBeUsed(string $expected, string $from, string $to, string $header): void { $differ = new Differ(new UnifiedDiffOutputBuilder($header)); $this->assertSame( $expected, $differ->diff($from, $to) ); } public function headerProvider(): array { return [ [ "CUSTOM HEADER\n@@ @@\n-a\n+b\n", 'a', 'b', 'CUSTOM HEADER', ], [ "CUSTOM HEADER\n@@ @@\n-a\n+b\n", 'a', 'b', "CUSTOM HEADER\n", ], [ "CUSTOM HEADER\n\n@@ @@\n-a\n+b\n", 'a', 'b', "CUSTOM HEADER\n\n", ], [ "@@ @@\n-a\n+b\n", 'a', 'b', '', ], ]; } /** * @param string $expected * @param string $from * @param string $to * * @dataProvider provideDiffWithLineNumbers */ public function testDiffWithLineNumbers($expected, $from, $to): void { $differ = new Differ(new UnifiedDiffOutputBuilder("--- Original\n+++ New\n", true)); $this->assertSame($expected, $differ->diff($from, $to)); } public function provideDiffWithLineNumbers(): array { return UnifiedDiffOutputBuilderDataProvider::provideDiffWithLineNumbers(); } } PK!R~)))Output/AbstractChunkOutputBuilderTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Diff\Output; use PHPUnit\Framework\TestCase; use SebastianBergmann\Diff\Differ; /** * @covers SebastianBergmann\Diff\Output\AbstractChunkOutputBuilder * * @uses SebastianBergmann\Diff\Differ * @uses SebastianBergmann\Diff\Output\UnifiedDiffOutputBuilder * @uses SebastianBergmann\Diff\TimeEfficientLongestCommonSubsequenceCalculator */ final class AbstractChunkOutputBuilderTest extends TestCase { /** * @param array $expected * @param string $from * @param string $to * @param int $lineThreshold * * @dataProvider provideGetCommonChunks */ public function testGetCommonChunks(array $expected, string $from, string $to, int $lineThreshold = 5): void { $output = new class extends AbstractChunkOutputBuilder { public function getDiff(array $diff): string { return ''; } public function getChunks(array $diff, $lineThreshold) { return $this->getCommonChunks($diff, $lineThreshold); } }; $this->assertSame( $expected, $output->getChunks((new Differ)->diffToArray($from, $to), $lineThreshold) ); } public function provideGetCommonChunks(): array { return[ 'same (with default threshold)' => [ [], 'A', 'A', ], 'same (threshold 0)' => [ [0 => 0], 'A', 'A', 0, ], 'empty' => [ [], '', '', ], 'single line diff' => [ [], 'A', 'B', ], 'below threshold I' => [ [], "A\nX\nC", "A\nB\nC", ], 'below threshold II' => [ [], "A\n\n\n\nX\nC", "A\n\n\n\nB\nC", ], 'below threshold III' => [ [0 => 5], "A\n\n\n\n\n\nB", "A\n\n\n\n\n\nA", ], 'same start' => [ [0 => 5], "A\n\n\n\n\n\nX\nC", "A\n\n\n\n\n\nB\nC", ], 'same start long' => [ [0 => 13], "\n\n\n\n\n\n\n\n\n\n\n\n\n\nA", "\n\n\n\n\n\n\n\n\n\n\n\n\n\nB", ], 'same part in between' => [ [2 => 8], "A\n\n\n\n\n\n\nX\nY\nZ\n\n", "B\n\n\n\n\n\n\nX\nA\nZ\n\n", ], 'same trailing' => [ [2 => 14], "A\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "B\n\n\n\n\n\n\n\n\n\n\n\n\n\n", ], 'same part in between, same trailing' => [ [2 => 7, 10 => 15], "A\n\n\n\n\n\n\nA\n\n\n\n\n\n\n", "B\n\n\n\n\n\n\nB\n\n\n\n\n\n\n", ], 'below custom threshold I' => [ [], "A\n\nB", "A\n\nD", 2, ], 'custom threshold I' => [ [0 => 1], "A\n\nB", "A\n\nD", 1, ], 'custom threshold II' => [ [], "A\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "A\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", 19, ], [ [3 => 9], "a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk", "a\np\nc\nd\ne\nf\ng\nh\ni\nw\nk", ], [ [0 => 5, 8 => 13], "A\nA\nA\nA\nA\nA\nX\nC\nC\nC\nC\nC\nC", "A\nA\nA\nA\nA\nA\nB\nC\nC\nC\nC\nC\nC", ], [ [0 => 5, 8 => 13], "A\nA\nA\nA\nA\nA\nX\nC\nC\nC\nC\nC\nC\nX", "A\nA\nA\nA\nA\nA\nB\nC\nC\nC\nC\nC\nC\nY", ], ]; } } PK! %y%MemoryEfficientImplementationTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Diff; /** * @covers SebastianBergmann\Diff\MemoryEfficientLongestCommonSubsequenceCalculator */ final class MemoryEfficientImplementationTest extends LongestCommonSubsequenceTest { protected function createImplementation(): LongestCommonSubsequenceCalculator { return new MemoryEfficientLongestCommonSubsequenceCalculator; } } PK!NEWhhCron/CronExpressionTest.phpnu[ */ class CronExpressionTest extends TestCase { /** * @covers \Cron\CronExpression::factory */ public function testFactoryRecognizesTemplates() { $this->assertSame('0 0 1 1 *', CronExpression::factory('@annually')->getExpression()); $this->assertSame('0 0 1 1 *', CronExpression::factory('@yearly')->getExpression()); $this->assertSame('0 0 * * 0', CronExpression::factory('@weekly')->getExpression()); } /** * @covers \Cron\CronExpression::__construct * @covers \Cron\CronExpression::getExpression * @covers \Cron\CronExpression::__toString */ public function testParsesCronSchedule() { // '2010-09-10 12:00:00' $cron = CronExpression::factory('1 2-4 * 4,5,6 */3'); $this->assertSame('1', $cron->getExpression(CronExpression::MINUTE)); $this->assertSame('2-4', $cron->getExpression(CronExpression::HOUR)); $this->assertSame('*', $cron->getExpression(CronExpression::DAY)); $this->assertSame('4,5,6', $cron->getExpression(CronExpression::MONTH)); $this->assertSame('*/3', $cron->getExpression(CronExpression::WEEKDAY)); $this->assertSame('1 2-4 * 4,5,6 */3', $cron->getExpression()); $this->assertSame('1 2-4 * 4,5,6 */3', (string) $cron); $this->assertNull($cron->getExpression('foo')); } /** * @covers \Cron\CronExpression::__construct * @covers \Cron\CronExpression::getExpression * @covers \Cron\CronExpression::__toString * @expectedException \InvalidArgumentException * @expectedExceptionMessage Invalid CRON field value A at position 0 */ public function testParsesCronScheduleThrowsAnException() { CronExpression::factory('A 1 2 3 4'); } /** * @covers \Cron\CronExpression::__construct * @covers \Cron\CronExpression::getExpression * @dataProvider scheduleWithDifferentSeparatorsProvider */ public function testParsesCronScheduleWithAnySpaceCharsAsSeparators($schedule, array $expected) { $cron = CronExpression::factory($schedule); $this->assertSame($expected[0], $cron->getExpression(CronExpression::MINUTE)); $this->assertSame($expected[1], $cron->getExpression(CronExpression::HOUR)); $this->assertSame($expected[2], $cron->getExpression(CronExpression::DAY)); $this->assertSame($expected[3], $cron->getExpression(CronExpression::MONTH)); $this->assertSame($expected[4], $cron->getExpression(CronExpression::WEEKDAY)); } /** * Data provider for testParsesCronScheduleWithAnySpaceCharsAsSeparators * * @return array */ public static function scheduleWithDifferentSeparatorsProvider() { return array( array("*\t*\t*\t*\t*\t", array('*', '*', '*', '*', '*', '*')), array("* * * * * ", array('*', '*', '*', '*', '*', '*')), array("* \t * \t * \t * \t * \t", array('*', '*', '*', '*', '*', '*')), array("*\t \t*\t \t*\t \t*\t \t*\t \t", array('*', '*', '*', '*', '*', '*')), ); } /** * @covers \Cron\CronExpression::__construct * @covers \Cron\CronExpression::setExpression * @covers \Cron\CronExpression::setPart * @expectedException InvalidArgumentException */ public function testInvalidCronsWillFail() { // Only four values $cron = CronExpression::factory('* * * 1'); } /** * @covers \Cron\CronExpression::setPart * @expectedException InvalidArgumentException */ public function testInvalidPartsWillFail() { // Only four values $cron = CronExpression::factory('* * * * *'); $cron->setPart(1, 'abc'); } /** * Data provider for cron schedule * * @return array */ public function scheduleProvider() { return array( array('*/2 */2 * * *', '2015-08-10 21:47:27', '2015-08-10 22:00:00', false), array('* * * * *', '2015-08-10 21:50:37', '2015-08-10 21:50:00', true), array('* 20,21,22 * * *', '2015-08-10 21:50:00', '2015-08-10 21:50:00', true), // Handles CSV values array('* 20,22 * * *', '2015-08-10 21:50:00', '2015-08-10 22:00:00', false), // CSV values can be complex array('7-9 * */9 * *', '2015-08-10 22:02:33', '2015-08-10 22:07:00', false), // 15th minute, of the second hour, every 15 days, in January, every Friday array('1 * * * 7', '2015-08-10 21:47:27', '2015-08-16 00:01:00', false), // Test with exact times array('47 21 * * *', strtotime('2015-08-10 21:47:30'), '2015-08-10 21:47:00', true), // Test Day of the week (issue #1) // According cron implementation, 0|7 = sunday, 1 => monday, etc array('* * * * 0', strtotime('2011-06-15 23:09:00'), '2011-06-19 00:00:00', false), array('* * * * 7', strtotime('2011-06-15 23:09:00'), '2011-06-19 00:00:00', false), array('* * * * 1', strtotime('2011-06-15 23:09:00'), '2011-06-20 00:00:00', false), // Should return the sunday date as 7 equals 0 array('0 0 * * MON,SUN', strtotime('2011-06-15 23:09:00'), '2011-06-19 00:00:00', false), array('0 0 * * 1,7', strtotime('2011-06-15 23:09:00'), '2011-06-19 00:00:00', false), array('0 0 * * 0-4', strtotime('2011-06-15 23:09:00'), '2011-06-16 00:00:00', false), array('0 0 * * 7-4', strtotime('2011-06-15 23:09:00'), '2011-06-16 00:00:00', false), array('0 0 * * 4-7', strtotime('2011-06-15 23:09:00'), '2011-06-16 00:00:00', false), array('0 0 * * 7-3', strtotime('2011-06-15 23:09:00'), '2011-06-19 00:00:00', false), array('0 0 * * 3-7', strtotime('2011-06-15 23:09:00'), '2011-06-16 00:00:00', false), array('0 0 * * 3-7', strtotime('2011-06-18 23:09:00'), '2011-06-19 00:00:00', false), // Test lists of values and ranges (Abhoryo) array('0 0 * * 2-7', strtotime('2011-06-20 23:09:00'), '2011-06-21 00:00:00', false), array('0 0 * * 2-7', strtotime('2011-06-18 23:09:00'), '2011-06-19 00:00:00', false), array('0 0 * * 4-7', strtotime('2011-07-19 00:00:00'), '2011-07-21 00:00:00', false), // Test increments of ranges array('0-12/4 * * * *', strtotime('2011-06-20 12:04:00'), '2011-06-20 12:04:00', true), array('4-59/2 * * * *', strtotime('2011-06-20 12:04:00'), '2011-06-20 12:04:00', true), array('4-59/2 * * * *', strtotime('2011-06-20 12:06:00'), '2011-06-20 12:06:00', true), array('4-59/3 * * * *', strtotime('2011-06-20 12:06:00'), '2011-06-20 12:07:00', false), // Test Day of the Week and the Day of the Month (issue #1) array('0 0 1 1 0', strtotime('2011-06-15 23:09:00'), '2012-01-01 00:00:00', false), array('0 0 1 JAN 0', strtotime('2011-06-15 23:09:00'), '2012-01-01 00:00:00', false), array('0 0 1 * 0', strtotime('2011-06-15 23:09:00'), '2012-01-01 00:00:00', false), // Test the W day of the week modifier for day of the month field array('0 0 2W * *', strtotime('2011-07-01 00:00:00'), '2011-07-01 00:00:00', true), array('0 0 1W * *', strtotime('2011-05-01 00:00:00'), '2011-05-02 00:00:00', false), array('0 0 1W * *', strtotime('2011-07-01 00:00:00'), '2011-07-01 00:00:00', true), array('0 0 3W * *', strtotime('2011-07-01 00:00:00'), '2011-07-04 00:00:00', false), array('0 0 16W * *', strtotime('2011-07-01 00:00:00'), '2011-07-15 00:00:00', false), array('0 0 28W * *', strtotime('2011-07-01 00:00:00'), '2011-07-28 00:00:00', false), array('0 0 30W * *', strtotime('2011-07-01 00:00:00'), '2011-07-29 00:00:00', false), array('0 0 31W * *', strtotime('2011-07-01 00:00:00'), '2011-07-29 00:00:00', false), // Test the last weekday of a month array('* * * * 5L', strtotime('2011-07-01 00:00:00'), '2011-07-29 00:00:00', false), array('* * * * 6L', strtotime('2011-07-01 00:00:00'), '2011-07-30 00:00:00', false), array('* * * * 7L', strtotime('2011-07-01 00:00:00'), '2011-07-31 00:00:00', false), array('* * * * 1L', strtotime('2011-07-24 00:00:00'), '2011-07-25 00:00:00', false), array('* * * 1 5L', strtotime('2011-12-25 00:00:00'), '2012-01-27 00:00:00', false), // Test the hash symbol for the nth weekday of a given month array('* * * * 5#2', strtotime('2011-07-01 00:00:00'), '2011-07-08 00:00:00', false), array('* * * * 5#1', strtotime('2011-07-01 00:00:00'), '2011-07-01 00:00:00', true), array('* * * * 3#4', strtotime('2011-07-01 00:00:00'), '2011-07-27 00:00:00', false), // Issue #7, documented example failed ['3-59/15 6-12 */15 1 2-5', strtotime('2017-01-08 00:00:00'), '2017-01-31 06:03:00', false], // https://github.com/laravel/framework/commit/07d160ac3cc9764d5b429734ffce4fa311385403 ['* * * * MON-FRI', strtotime('2017-01-08 00:00:00'), strtotime('2017-01-09 00:00:00'), false], ['* * * * TUE', strtotime('2017-01-08 00:00:00'), strtotime('2017-01-10 00:00:00'), false], ); } /** * @covers \Cron\CronExpression::isDue * @covers \Cron\CronExpression::getNextRunDate * @covers \Cron\DayOfMonthField * @covers \Cron\DayOfWeekField * @covers \Cron\MinutesField * @covers \Cron\HoursField * @covers \Cron\MonthField * @covers \Cron\CronExpression::getRunDate * @dataProvider scheduleProvider */ public function testDeterminesIfCronIsDue($schedule, $relativeTime, $nextRun, $isDue) { $relativeTimeString = is_int($relativeTime) ? date('Y-m-d H:i:s', $relativeTime) : $relativeTime; // Test next run date $cron = CronExpression::factory($schedule); if (is_string($relativeTime)) { $relativeTime = new DateTime($relativeTime); } elseif (is_int($relativeTime)) { $relativeTime = date('Y-m-d H:i:s', $relativeTime); } if (is_string($nextRun)) { $nextRunDate = new DateTime($nextRun); } elseif (is_int($nextRun)) { $nextRunDate = new DateTime(); $nextRunDate->setTimestamp($nextRun); } $this->assertSame($isDue, $cron->isDue($relativeTime)); $next = $cron->getNextRunDate($relativeTime, 0, true); $this->assertEquals($nextRunDate, $next); } /** * @covers \Cron\CronExpression::isDue */ public function testIsDueHandlesDifferentDates() { $cron = CronExpression::factory('* * * * *'); $this->assertTrue($cron->isDue()); $this->assertTrue($cron->isDue('now')); $this->assertTrue($cron->isDue(new DateTime('now'))); $this->assertTrue($cron->isDue(date('Y-m-d H:i'))); $this->assertTrue($cron->isDue(new DateTimeImmutable('now'))); } /** * @covers \Cron\CronExpression::isDue */ public function testIsDueHandlesDifferentDefaultTimezones() { $originalTimezone = date_default_timezone_get(); $cron = CronExpression::factory('0 15 * * 3'); //Wednesday at 15:00 $date = '2014-01-01 15:00'; //Wednesday date_default_timezone_set('UTC'); $this->assertTrue($cron->isDue(new DateTime($date), 'UTC')); $this->assertFalse($cron->isDue(new DateTime($date), 'Europe/Amsterdam')); $this->assertFalse($cron->isDue(new DateTime($date), 'Asia/Tokyo')); date_default_timezone_set('Europe/Amsterdam'); $this->assertFalse($cron->isDue(new DateTime($date), 'UTC')); $this->assertTrue($cron->isDue(new DateTime($date), 'Europe/Amsterdam')); $this->assertFalse($cron->isDue(new DateTime($date), 'Asia/Tokyo')); date_default_timezone_set('Asia/Tokyo'); $this->assertFalse($cron->isDue(new DateTime($date), 'UTC')); $this->assertFalse($cron->isDue(new DateTime($date), 'Europe/Amsterdam')); $this->assertTrue($cron->isDue(new DateTime($date), 'Asia/Tokyo')); date_default_timezone_set($originalTimezone); } /** * @covers \Cron\CronExpression::isDue */ public function testIsDueHandlesDifferentSuppliedTimezones() { $cron = CronExpression::factory('0 15 * * 3'); //Wednesday at 15:00 $date = '2014-01-01 15:00'; //Wednesday $this->assertTrue($cron->isDue(new DateTime($date, new DateTimeZone('UTC')), 'UTC')); $this->assertFalse($cron->isDue(new DateTime($date, new DateTimeZone('UTC')), 'Europe/Amsterdam')); $this->assertFalse($cron->isDue(new DateTime($date, new DateTimeZone('UTC')), 'Asia/Tokyo')); $this->assertFalse($cron->isDue(new DateTime($date, new DateTimeZone('Europe/Amsterdam')), 'UTC')); $this->assertTrue($cron->isDue(new DateTime($date, new DateTimeZone('Europe/Amsterdam')), 'Europe/Amsterdam')); $this->assertFalse($cron->isDue(new DateTime($date, new DateTimeZone('Europe/Amsterdam')), 'Asia/Tokyo')); $this->assertFalse($cron->isDue(new DateTime($date, new DateTimeZone('Asia/Tokyo')), 'UTC')); $this->assertFalse($cron->isDue(new DateTime($date, new DateTimeZone('Asia/Tokyo')), 'Europe/Amsterdam')); $this->assertTrue($cron->isDue(new DateTime($date, new DateTimeZone('Asia/Tokyo')), 'Asia/Tokyo')); } /** * @covers Cron\CronExpression::isDue */ public function testIsDueHandlesDifferentTimezonesAsArgument() { $cron = CronExpression::factory('0 15 * * 3'); //Wednesday at 15:00 $date = '2014-01-01 15:00'; //Wednesday $utc = new \DateTimeZone('UTC'); $amsterdam = new \DateTimeZone('Europe/Amsterdam'); $tokyo = new \DateTimeZone('Asia/Tokyo'); $this->assertTrue($cron->isDue(new DateTime($date, $utc), 'UTC')); $this->assertFalse($cron->isDue(new DateTime($date, $amsterdam), 'UTC')); $this->assertFalse($cron->isDue(new DateTime($date, $tokyo), 'UTC')); $this->assertFalse($cron->isDue(new DateTime($date, $utc), 'Europe/Amsterdam')); $this->assertTrue($cron->isDue(new DateTime($date, $amsterdam), 'Europe/Amsterdam')); $this->assertFalse($cron->isDue(new DateTime($date, $tokyo), 'Europe/Amsterdam')); $this->assertFalse($cron->isDue(new DateTime($date, $utc), 'Asia/Tokyo')); $this->assertFalse($cron->isDue(new DateTime($date, $amsterdam), 'Asia/Tokyo')); $this->assertTrue($cron->isDue(new DateTime($date, $tokyo), 'Asia/Tokyo')); } /** * @covers Cron\CronExpression::isDue */ public function testRecognisesTimezonesAsPartOfDateTime() { $cron = CronExpression::factory("0 7 * * *"); $tzCron = "America/New_York"; $tzServer = new \DateTimeZone("Europe/London"); $dtCurrent = \DateTime::createFromFormat("!Y-m-d H:i:s", "2017-10-17 10:00:00", $tzServer); $dtPrev = $cron->getPreviousRunDate($dtCurrent, 0, true, $tzCron); $this->assertEquals('1508151600 : 2017-10-16T07:00:00-04:00 : America/New_York', $dtPrev->format("U \: c \: e")); $dtCurrent = \DateTimeImmutable::createFromFormat("!Y-m-d H:i:s", "2017-10-17 10:00:00", $tzServer); $dtPrev = $cron->getPreviousRunDate($dtCurrent, 0, true, $tzCron); $this->assertEquals('1508151600 : 2017-10-16T07:00:00-04:00 : America/New_York', $dtPrev->format("U \: c \: e")); $dtCurrent = \DateTimeImmutable::createFromFormat("!Y-m-d H:i:s", "2017-10-17 10:00:00", $tzServer); $dtPrev = $cron->getPreviousRunDate($dtCurrent->format("c"), 0, true, $tzCron); $this->assertEquals('1508151600 : 2017-10-16T07:00:00-04:00 : America/New_York', $dtPrev->format("U \: c \: e")); $dtCurrent = \DateTimeImmutable::createFromFormat("!Y-m-d H:i:s", "2017-10-17 10:00:00", $tzServer); $dtPrev = $cron->getPreviousRunDate($dtCurrent->format("\@U"), 0, true, $tzCron); $this->assertEquals('1508151600 : 2017-10-16T07:00:00-04:00 : America/New_York', $dtPrev->format("U \: c \: e")); } /** * @covers \Cron\CronExpression::getPreviousRunDate */ public function testCanGetPreviousRunDates() { $cron = CronExpression::factory('* * * * *'); $next = $cron->getNextRunDate('now'); $two = $cron->getNextRunDate('now', 1); $this->assertEquals($next, $cron->getPreviousRunDate($two)); $cron = CronExpression::factory('* */2 * * *'); $next = $cron->getNextRunDate('now'); $two = $cron->getNextRunDate('now', 1); $this->assertEquals($next, $cron->getPreviousRunDate($two)); $cron = CronExpression::factory('* * * */2 *'); $next = $cron->getNextRunDate('now'); $two = $cron->getNextRunDate('now', 1); $this->assertEquals($next, $cron->getPreviousRunDate($two)); } /** * @covers \Cron\CronExpression::getMultipleRunDates */ public function testProvidesMultipleRunDates() { $cron = CronExpression::factory('*/2 * * * *'); $this->assertEquals(array( new DateTime('2008-11-09 00:00:00'), new DateTime('2008-11-09 00:02:00'), new DateTime('2008-11-09 00:04:00'), new DateTime('2008-11-09 00:06:00') ), $cron->getMultipleRunDates(4, '2008-11-09 00:00:00', false, true)); } /** * @covers \Cron\CronExpression::getMultipleRunDates * @covers \Cron\CronExpression::setMaxIterationCount */ public function testProvidesMultipleRunDatesForTheFarFuture() { // Fails with the default 1000 iteration limit $cron = CronExpression::factory('0 0 12 1 *'); $cron->setMaxIterationCount(2000); $this->assertEquals(array( new DateTime('2016-01-12 00:00:00'), new DateTime('2017-01-12 00:00:00'), new DateTime('2018-01-12 00:00:00'), new DateTime('2019-01-12 00:00:00'), new DateTime('2020-01-12 00:00:00'), new DateTime('2021-01-12 00:00:00'), new DateTime('2022-01-12 00:00:00'), new DateTime('2023-01-12 00:00:00'), new DateTime('2024-01-12 00:00:00'), ), $cron->getMultipleRunDates(9, '2015-04-28 00:00:00', false, true)); } /** * @covers \Cron\CronExpression */ public function testCanIterateOverNextRuns() { $cron = CronExpression::factory('@weekly'); $nextRun = $cron->getNextRunDate("2008-11-09 08:00:00"); $this->assertEquals($nextRun, new DateTime("2008-11-16 00:00:00")); // true is cast to 1 $nextRun = $cron->getNextRunDate("2008-11-09 00:00:00", true, true); $this->assertEquals($nextRun, new DateTime("2008-11-16 00:00:00")); // You can iterate over them $nextRun = $cron->getNextRunDate($cron->getNextRunDate("2008-11-09 00:00:00", 1, true), 1, true); $this->assertEquals($nextRun, new DateTime("2008-11-23 00:00:00")); // You can skip more than one $nextRun = $cron->getNextRunDate("2008-11-09 00:00:00", 2, true); $this->assertEquals($nextRun, new DateTime("2008-11-23 00:00:00")); $nextRun = $cron->getNextRunDate("2008-11-09 00:00:00", 3, true); $this->assertEquals($nextRun, new DateTime("2008-11-30 00:00:00")); } /** * @covers \Cron\CronExpression::getRunDate */ public function testGetRunDateHandlesDifferentDates() { $cron = CronExpression::factory('@weekly'); $date = new DateTime("2019-03-10 00:00:00"); $this->assertEquals($date, $cron->getNextRunDate("2019-03-03 08:00:00")); $this->assertEquals($date, $cron->getNextRunDate(new DateTime("2019-03-03 08:00:00"))); $this->assertEquals($date, $cron->getNextRunDate(new DateTimeImmutable("2019-03-03 08:00:00"))); } /** * @covers \Cron\CronExpression::getRunDate */ public function testSkipsCurrentDateByDefault() { $cron = CronExpression::factory('* * * * *'); $current = new DateTime('now'); $next = $cron->getNextRunDate($current); $nextPrev = $cron->getPreviousRunDate($next); $this->assertSame($current->format('Y-m-d H:i:00'), $nextPrev->format('Y-m-d H:i:s')); } /** * @covers \Cron\CronExpression::getRunDate * @ticket 7 */ public function testStripsForSeconds() { $cron = CronExpression::factory('* * * * *'); $current = new DateTime('2011-09-27 10:10:54'); $this->assertSame('2011-09-27 10:11:00', $cron->getNextRunDate($current)->format('Y-m-d H:i:s')); } /** * @covers \Cron\CronExpression::getRunDate */ public function testFixesPhpBugInDateIntervalMonth() { $cron = CronExpression::factory('0 0 27 JAN *'); $this->assertSame('2011-01-27 00:00:00', $cron->getPreviousRunDate('2011-08-22 00:00:00')->format('Y-m-d H:i:s')); } public function testIssue29() { $cron = CronExpression::factory('@weekly'); $this->assertSame( '2013-03-10 00:00:00', $cron->getPreviousRunDate('2013-03-17 00:00:00')->format('Y-m-d H:i:s') ); } /** * @see https://github.com/mtdowling/cron-expression/issues/20 */ public function testIssue20() { $e = CronExpression::factory('* * * * MON#1'); $this->assertTrue($e->isDue(new DateTime('2014-04-07 00:00:00'))); $this->assertFalse($e->isDue(new DateTime('2014-04-14 00:00:00'))); $this->assertFalse($e->isDue(new DateTime('2014-04-21 00:00:00'))); $e = CronExpression::factory('* * * * SAT#2'); $this->assertFalse($e->isDue(new DateTime('2014-04-05 00:00:00'))); $this->assertTrue($e->isDue(new DateTime('2014-04-12 00:00:00'))); $this->assertFalse($e->isDue(new DateTime('2014-04-19 00:00:00'))); $e = CronExpression::factory('* * * * SUN#3'); $this->assertFalse($e->isDue(new DateTime('2014-04-13 00:00:00'))); $this->assertTrue($e->isDue(new DateTime('2014-04-20 00:00:00'))); $this->assertFalse($e->isDue(new DateTime('2014-04-27 00:00:00'))); } /** * @covers \Cron\CronExpression::getRunDate */ public function testKeepOriginalTime() { $now = new \DateTime; $strNow = $now->format(DateTime::ISO8601); $cron = CronExpression::factory('0 0 * * *'); $cron->getPreviousRunDate($now); $this->assertSame($strNow, $now->format(DateTime::ISO8601)); } /** * @covers \Cron\CronExpression::__construct * @covers \Cron\CronExpression::factory * @covers \Cron\CronExpression::isValidExpression * @covers \Cron\CronExpression::setExpression * @covers \Cron\CronExpression::setPart */ public function testValidationWorks() { // Invalid. Only four values $this->assertFalse(CronExpression::isValidExpression('* * * 1')); // Valid $this->assertTrue(CronExpression::isValidExpression('* * * * 1')); // Issue #156, 13 is an invalid month $this->assertFalse(CronExpression::isValidExpression("* * * 13 * ")); // Issue #155, 90 is an invalid second $this->assertFalse(CronExpression::isValidExpression('90 * * * *')); // Issue #154, 24 is an invalid hour $this->assertFalse(CronExpression::isValidExpression("0 24 1 12 0")); // Issue #125, this is just all sorts of wrong $this->assertFalse(CronExpression::isValidExpression('990 14 * * mon-fri0345345')); // see https://github.com/dragonmantank/cron-expression/issues/5 $this->assertTrue(CronExpression::isValidExpression('2,17,35,47 5-7,11-13 * * *')); } /** * Makes sure that 00 is considered a valid value for 0-based fields * cronie allows numbers with a leading 0, so adding support for this as well * * @see https://github.com/dragonmantank/cron-expression/issues/12 */ public function testDoubleZeroIsValid() { $this->assertTrue(CronExpression::isValidExpression('00 * * * *')); $this->assertTrue(CronExpression::isValidExpression('01 * * * *')); $this->assertTrue(CronExpression::isValidExpression('* 00 * * *')); $this->assertTrue(CronExpression::isValidExpression('* 01 * * *')); $e = CronExpression::factory('00 * * * *'); $this->assertTrue($e->isDue(new DateTime('2014-04-07 00:00:00'))); $e = CronExpression::factory('01 * * * *'); $this->assertTrue($e->isDue(new DateTime('2014-04-07 00:01:00'))); $e = CronExpression::factory('* 00 * * *'); $this->assertTrue($e->isDue(new DateTime('2014-04-07 00:00:00'))); $e = CronExpression::factory('* 01 * * *'); $this->assertTrue($e->isDue(new DateTime('2014-04-07 01:00:00'))); } /** * Ranges with large steps should "wrap around" to the appropriate value * cronie allows for steps that are larger than the range of a field, with it wrapping around like a ring buffer. We * should do the same. * * @see https://github.com/dragonmantank/cron-expression/issues/6 */ public function testRangesWrapAroundWithLargeSteps() { $f = new MonthField(); $this->assertTrue($f->validate('*/123')); $this->assertSame([4], $f->getRangeForExpression('*/123', 12)); $e = CronExpression::factory('* * * */123 *'); $this->assertTrue($e->isDue(new DateTime('2014-04-07 00:00:00'))); $nextRunDate = $e->getNextRunDate(new DateTime('2014-04-07 00:00:00')); $this->assertSame('2014-04-07 00:01:00', $nextRunDate->format('Y-m-d H:i:s')); $nextRunDate = $e->getNextRunDate(new DateTime('2014-05-07 00:00:00')); $this->assertSame('2015-04-01 00:00:00', $nextRunDate->format('Y-m-d H:i:s')); } /** * When there is an issue with a field, we should report the human readable position * * @see https://github.com/dragonmantank/cron-expression/issues/29 */ public function testFieldPositionIsHumanAdjusted() { $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage("6 is not a valid position"); $e = CronExpression::factory('0 * * * * ? *'); } } PK!;<<Cron/DayOfMonthFieldTest.phpnu[ */ class DayOfMonthFieldTest extends TestCase { /** * @covers \Cron\DayOfMonthField::validate */ public function testValidatesField() { $f = new DayOfMonthField(); $this->assertTrue($f->validate('1')); $this->assertTrue($f->validate('*')); $this->assertTrue($f->validate('L')); $this->assertTrue($f->validate('5W')); $this->assertTrue($f->validate('01')); $this->assertFalse($f->validate('5W,L')); $this->assertFalse($f->validate('1.')); } /** * @covers \Cron\DayOfMonthField::isSatisfiedBy */ public function testChecksIfSatisfied() { $f = new DayOfMonthField(); $this->assertTrue($f->isSatisfiedBy(new DateTime(), '?')); $this->assertTrue($f->isSatisfiedBy(new DateTimeImmutable(), '?')); } /** * @covers \Cron\DayOfMonthField::increment */ public function testIncrementsDate() { $d = new DateTime('2011-03-15 11:15:00'); $f = new DayOfMonthField(); $f->increment($d); $this->assertSame('2011-03-16 00:00:00', $d->format('Y-m-d H:i:s')); $d = new DateTime('2011-03-15 11:15:00'); $f->increment($d, true); $this->assertSame('2011-03-14 23:59:00', $d->format('Y-m-d H:i:s')); } /** * @covers \Cron\DayOfMonthField::increment */ public function testIncrementsDateTimeImmutable() { $d = new DateTimeImmutable('2011-03-15 11:15:00'); $f = new DayOfMonthField(); $f->increment($d); $this->assertSame('2011-03-16 00:00:00', $d->format('Y-m-d H:i:s')); } /** * Day of the month cannot accept a 0 value, it must be between 1 and 31 * See Github issue #120 * * @since 2017-01-22 */ public function testDoesNotAccept0Date() { $f = new DayOfMonthField(); $this->assertFalse($f->validate(0)); } } PK!; ; Cron/HoursFieldTest.phpnu[ */ class HoursFieldTest extends TestCase { /** * @covers \Cron\HoursField::validate */ public function testValidatesField() { $f = new HoursField(); $this->assertTrue($f->validate('1')); $this->assertTrue($f->validate('00')); $this->assertTrue($f->validate('01')); $this->assertTrue($f->validate('*')); $this->assertFalse($f->validate('*/3,1,1-12')); } /** * @covers \Cron\HoursField::isSatisfiedBy */ public function testChecksIfSatisfied() { $f = new HoursField(); $this->assertTrue($f->isSatisfiedBy(new DateTime(), '?')); $this->assertTrue($f->isSatisfiedBy(new DateTimeImmutable(), '?')); } /** * @covers \Cron\HoursField::increment */ public function testIncrementsDate() { $d = new DateTime('2011-03-15 11:15:00'); $f = new HoursField(); $f->increment($d); $this->assertSame('2011-03-15 12:00:00', $d->format('Y-m-d H:i:s')); $d->setTime(11, 15, 0); $f->increment($d, true); $this->assertSame('2011-03-15 10:59:00', $d->format('Y-m-d H:i:s')); } /** * @covers \Cron\HoursField::increment */ public function testIncrementsDateTimeImmutable() { $d = new DateTimeImmutable('2011-03-15 11:15:00'); $f = new HoursField(); $f->increment($d); $this->assertSame('2011-03-15 12:00:00', $d->format('Y-m-d H:i:s')); } /** * @covers \Cron\HoursField::increment */ public function testIncrementsDateWithThirtyMinuteOffsetTimezone() { $tz = date_default_timezone_get(); date_default_timezone_set('America/St_Johns'); $d = new DateTime('2011-03-15 11:15:00'); $f = new HoursField(); $f->increment($d); $this->assertSame('2011-03-15 12:00:00', $d->format('Y-m-d H:i:s')); $d->setTime(11, 15, 0); $f->increment($d, true); $this->assertSame('2011-03-15 10:59:00', $d->format('Y-m-d H:i:s')); date_default_timezone_set($tz); } /** * @covers \Cron\HoursField::increment */ public function testIncrementDateWithFifteenMinuteOffsetTimezone() { $tz = date_default_timezone_get(); date_default_timezone_set('Asia/Kathmandu'); $d = new DateTime('2011-03-15 11:15:00'); $f = new HoursField(); $f->increment($d); $this->assertSame('2011-03-15 12:00:00', $d->format('Y-m-d H:i:s')); $d->setTime(11, 15, 0); $f->increment($d, true); $this->assertSame('2011-03-15 10:59:00', $d->format('Y-m-d H:i:s')); date_default_timezone_set($tz); } } PK!8Cron/FieldFactoryTest.phpnu[ */ class FieldFactoryTest extends TestCase { /** * @covers \Cron\FieldFactory::getField */ public function testRetrievesFieldInstances() { $mappings = array( 0 => 'Cron\MinutesField', 1 => 'Cron\HoursField', 2 => 'Cron\DayOfMonthField', 3 => 'Cron\MonthField', 4 => 'Cron\DayOfWeekField', ); $f = new FieldFactory(); foreach ($mappings as $position => $class) { $this->assertSame($class, get_class($f->getField($position))); } } /** * @covers \Cron\FieldFactory::getField * @expectedException InvalidArgumentException */ public function testValidatesFieldPosition() { $f = new FieldFactory(); $f->getField(-1); } } PK!e&C C Cron/MonthFieldTest.phpnu[ */ class MonthFieldTest extends TestCase { /** * @covers \Cron\MonthField::validate */ public function testValidatesField() { $f = new MonthField(); $this->assertTrue($f->validate('12')); $this->assertTrue($f->validate('*')); $this->assertFalse($f->validate('*/10,2,1-12')); $this->assertFalse($f->validate('1.fix-regexp')); } /** * @covers \Cron\MonthField::isSatisfiedBy */ public function testChecksIfSatisfied() { $f = new MonthField(); $this->assertTrue($f->isSatisfiedBy(new DateTime(), '?')); $this->assertTrue($f->isSatisfiedBy(new DateTimeImmutable(), '?')); } /** * @covers \Cron\MonthField::increment */ public function testIncrementsDate() { $d = new DateTime('2011-03-15 11:15:00'); $f = new MonthField(); $f->increment($d); $this->assertSame('2011-04-01 00:00:00', $d->format('Y-m-d H:i:s')); $d = new DateTime('2011-03-15 11:15:00'); $f->increment($d, true); $this->assertSame('2011-02-28 23:59:00', $d->format('Y-m-d H:i:s')); } /** * @covers \Cron\MonthField::increment */ public function testIncrementsDateTimeImmutable() { $d = new DateTimeImmutable('2011-03-15 11:15:00'); $f = new MonthField(); $f->increment($d); $this->assertSame('2011-04-01 00:00:00', $d->format('Y-m-d H:i:s')); } /** * @covers \Cron\MonthField::increment */ public function testIncrementsDateWithThirtyMinuteTimezone() { $tz = date_default_timezone_get(); date_default_timezone_set('America/St_Johns'); $d = new DateTime('2011-03-31 11:59:59'); $f = new MonthField(); $f->increment($d); $this->assertSame('2011-04-01 00:00:00', $d->format('Y-m-d H:i:s')); $d = new DateTime('2011-03-15 11:15:00'); $f->increment($d, true); $this->assertSame('2011-02-28 23:59:00', $d->format('Y-m-d H:i:s')); date_default_timezone_set($tz); } /** * @covers \Cron\MonthField::increment */ public function testIncrementsYearAsNeeded() { $f = new MonthField(); $d = new DateTime('2011-12-15 00:00:00'); $f->increment($d); $this->assertSame('2012-01-01 00:00:00', $d->format('Y-m-d H:i:s')); } /** * @covers \Cron\MonthField::increment */ public function testDecrementsYearAsNeeded() { $f = new MonthField(); $d = new DateTime('2011-01-15 00:00:00'); $f->increment($d, true); $this->assertSame('2010-12-31 23:59:00', $d->format('Y-m-d H:i:s')); } } PK!0|wwCron/DayOfWeekFieldTest.phpnu[ */ class DayOfWeekFieldTest extends TestCase { /** * @covers \Cron\DayOfWeekField::validate */ public function testValidatesField() { $f = new DayOfWeekField(); $this->assertTrue($f->validate('1')); $this->assertTrue($f->validate('01')); $this->assertTrue($f->validate('00')); $this->assertTrue($f->validate('*')); $this->assertFalse($f->validate('*/3,1,1-12')); $this->assertTrue($f->validate('SUN-2')); $this->assertFalse($f->validate('1.')); } /** * @covers \Cron\DayOfWeekField::isSatisfiedBy */ public function testChecksIfSatisfied() { $f = new DayOfWeekField(); $this->assertTrue($f->isSatisfiedBy(new DateTime(), '?')); $this->assertTrue($f->isSatisfiedBy(new DateTimeImmutable(), '?')); } /** * @covers \Cron\DayOfWeekField::increment */ public function testIncrementsDate() { $d = new DateTime('2011-03-15 11:15:00'); $f = new DayOfWeekField(); $f->increment($d); $this->assertSame('2011-03-16 00:00:00', $d->format('Y-m-d H:i:s')); $d = new DateTime('2011-03-15 11:15:00'); $f->increment($d, true); $this->assertSame('2011-03-14 23:59:00', $d->format('Y-m-d H:i:s')); } /** * @covers \Cron\DayOfWeekField::increment */ public function testIncrementsDateTimeImmutable() { $d = new DateTimeImmutable('2011-03-15 11:15:00'); $f = new DayOfWeekField(); $f->increment($d); $this->assertSame('2011-03-16 00:00:00', $d->format('Y-m-d H:i:s')); } /** * @covers \Cron\DayOfWeekField::isSatisfiedBy * @expectedException InvalidArgumentException * @expectedExceptionMessage Weekday must be a value between 0 and 7. 12 given */ public function testValidatesHashValueWeekday() { $f = new DayOfWeekField(); $this->assertTrue($f->isSatisfiedBy(new DateTime(), '12#1')); } /** * @covers \Cron\DayOfWeekField::isSatisfiedBy * @expectedException InvalidArgumentException * @expectedExceptionMessage There are never more than 5 or less than 1 of a given weekday in a month */ public function testValidatesHashValueNth() { $f = new DayOfWeekField(); $this->assertTrue($f->isSatisfiedBy(new DateTime(), '3#6')); } /** * @covers \Cron\DayOfWeekField::validate */ public function testValidateWeekendHash() { $f = new DayOfWeekField(); $this->assertTrue($f->validate('MON#1')); $this->assertTrue($f->validate('TUE#2')); $this->assertTrue($f->validate('WED#3')); $this->assertTrue($f->validate('THU#4')); $this->assertTrue($f->validate('FRI#5')); $this->assertTrue($f->validate('SAT#1')); $this->assertTrue($f->validate('SUN#3')); $this->assertTrue($f->validate('MON#1,MON#3')); } /** * @covers \Cron\DayOfWeekField::isSatisfiedBy */ public function testHandlesZeroAndSevenDayOfTheWeekValues() { $f = new DayOfWeekField(); $this->assertTrue($f->isSatisfiedBy(new DateTime('2011-09-04 00:00:00'), '0-2')); $this->assertTrue($f->isSatisfiedBy(new DateTime('2011-09-04 00:00:00'), '6-0')); $this->assertTrue($f->isSatisfiedBy(new DateTime('2014-04-20 00:00:00'), 'SUN')); $this->assertTrue($f->isSatisfiedBy(new DateTime('2014-04-20 00:00:00'), 'SUN#3')); $this->assertTrue($f->isSatisfiedBy(new DateTime('2014-04-20 00:00:00'), '0#3')); $this->assertTrue($f->isSatisfiedBy(new DateTime('2014-04-20 00:00:00'), '7#3')); } /** * @covers \Cron\DayOfWeekField::isSatisfiedBy */ public function testHandlesLastWeekdayOfTheMonth() { $f = new DayOfWeekField(); $this->assertTrue($f->isSatisfiedBy(new DateTime('2018-12-28 00:00:00'), 'FRIL')); $this->assertTrue($f->isSatisfiedBy(new DateTime('2018-12-28 00:00:00'), '5L')); $this->assertFalse($f->isSatisfiedBy(new DateTime('2018-12-21 00:00:00'), 'FRIL')); $this->assertFalse($f->isSatisfiedBy(new DateTime('2018-12-21 00:00:00'), '5L')); } /** * @see https://github.com/mtdowling/cron-expression/issues/47 */ public function testIssue47() { $f = new DayOfWeekField(); $this->assertFalse($f->validate('mon,')); $this->assertFalse($f->validate('mon-')); $this->assertFalse($f->validate('*/2,')); $this->assertFalse($f->validate('-mon')); $this->assertFalse($f->validate(',1')); $this->assertFalse($f->validate('*-')); $this->assertFalse($f->validate(',-')); } /** * @see https://github.com/laravel/framework/commit/07d160ac3cc9764d5b429734ffce4fa311385403 */ public function testLiteralsExpandProperly() { $f = new DayOfWeekField(); $this->assertTrue($f->validate('MON-FRI')); $this->assertSame([1,2,3,4,5], $f->getRangeForExpression('MON-FRI', 7)); } } PK!OCron/AbstractFieldTest.phpnu[ */ class AbstractFieldTest extends TestCase { /** * @covers \Cron\AbstractField::isRange */ public function testTestsIfRange() { $f = new DayOfWeekField(); $this->assertTrue($f->isRange('1-2')); $this->assertFalse($f->isRange('2')); } /** * @covers \Cron\AbstractField::isIncrementsOfRanges */ public function testTestsIfIncrementsOfRanges() { $f = new DayOfWeekField(); $this->assertFalse($f->isIncrementsOfRanges('1-2')); $this->assertTrue($f->isIncrementsOfRanges('1/2')); $this->assertTrue($f->isIncrementsOfRanges('*/2')); $this->assertTrue($f->isIncrementsOfRanges('3-12/2')); } /** * @covers \Cron\AbstractField::isInRange */ public function testTestsIfInRange() { $f = new DayOfWeekField(); $this->assertTrue($f->isInRange('1', '1-2')); $this->assertTrue($f->isInRange('2', '1-2')); $this->assertTrue($f->isInRange('5', '4-12')); $this->assertFalse($f->isInRange('3', '4-12')); $this->assertFalse($f->isInRange('13', '4-12')); } /** * @covers \Cron\AbstractField::isInIncrementsOfRanges */ public function testTestsIfInIncrementsOfRangesOnZeroStartRange() { $f = new MinutesField(); $this->assertTrue($f->isInIncrementsOfRanges('3', '3-59/2')); $this->assertTrue($f->isInIncrementsOfRanges('13', '3-59/2')); $this->assertTrue($f->isInIncrementsOfRanges('15', '3-59/2')); $this->assertTrue($f->isInIncrementsOfRanges('14', '*/2')); $this->assertFalse($f->isInIncrementsOfRanges('2', '3-59/13')); $this->assertFalse($f->isInIncrementsOfRanges('14', '*/13')); $this->assertFalse($f->isInIncrementsOfRanges('14', '3-59/2')); $this->assertFalse($f->isInIncrementsOfRanges('3', '2-59')); $this->assertFalse($f->isInIncrementsOfRanges('3', '2')); $this->assertFalse($f->isInIncrementsOfRanges('3', '*')); $this->assertFalse($f->isInIncrementsOfRanges('0', '*/0')); $this->assertFalse($f->isInIncrementsOfRanges('1', '*/0')); $this->assertTrue($f->isInIncrementsOfRanges('4', '4/1')); $this->assertFalse($f->isInIncrementsOfRanges('14', '4/1')); $this->assertFalse($f->isInIncrementsOfRanges('34', '4/1')); } /** * @covers \Cron\AbstractField::isInIncrementsOfRanges */ public function testTestsIfInIncrementsOfRangesOnOneStartRange() { $f = new MonthField(); $this->assertTrue($f->isInIncrementsOfRanges('3', '3-12/2')); $this->assertFalse($f->isInIncrementsOfRanges('13', '3-12/2')); $this->assertFalse($f->isInIncrementsOfRanges('15', '3-12/2')); $this->assertTrue($f->isInIncrementsOfRanges('3', '*/2')); $this->assertFalse($f->isInIncrementsOfRanges('3', '*/3')); $this->assertTrue($f->isInIncrementsOfRanges('7', '*/3')); $this->assertFalse($f->isInIncrementsOfRanges('14', '3-12/2')); $this->assertFalse($f->isInIncrementsOfRanges('3', '2-12')); $this->assertFalse($f->isInIncrementsOfRanges('3', '2')); $this->assertFalse($f->isInIncrementsOfRanges('3', '*')); $this->assertFalse($f->isInIncrementsOfRanges('0', '*/0')); $this->assertFalse($f->isInIncrementsOfRanges('1', '*/0')); $this->assertTrue($f->isInIncrementsOfRanges('4', '4/1')); $this->assertFalse($f->isInIncrementsOfRanges('14', '4/1')); $this->assertFalse($f->isInIncrementsOfRanges('34', '4/1')); } /** * @covers \Cron\AbstractField::isSatisfied */ public function testTestsIfSatisfied() { $f = new DayOfWeekField(); $this->assertTrue($f->isSatisfied('12', '3-13')); $this->assertFalse($f->isSatisfied('15', '3-7/2')); $this->assertTrue($f->isSatisfied('12', '*')); $this->assertTrue($f->isSatisfied('12', '12')); $this->assertFalse($f->isSatisfied('12', '3-11')); $this->assertFalse($f->isSatisfied('12', '3-7/2')); $this->assertFalse($f->isSatisfied('12', '11')); } /** * Allows ranges and lists to coexist in the same expression * * @see https://github.com/dragonmantank/cron-expression/issues/5 */ public function testAllowRangesAndLists() { $expression = '5-7,11-13'; $f = new HoursField(); $this->assertTrue($f->validate($expression)); } /** * Makes sure that various types of ranges expand out properly * * @see https://github.com/dragonmantank/cron-expression/issues/5 */ public function testGetRangeForExpressionExpandsCorrectly() { $f = new HoursField(); $this->assertSame([5, 6, 7, 11, 12, 13], $f->getRangeForExpression('5-7,11-13', 23)); $this->assertSame(['5', '6', '7', '11', '12', '13'], $f->getRangeForExpression('5,6,7,11,12,13', 23)); $this->assertSame([0, 6, 12, 18], $f->getRangeForExpression('*/6', 23)); $this->assertSame([5, 11], $f->getRangeForExpression('5-13/6', 23)); } } PK!oCron/MinutesFieldTest.phpnu[ */ class MinutesFieldTest extends TestCase { /** * @covers \Cron\MinutesField::validate */ public function testValidatesField() { $f = new MinutesField(); $this->assertTrue($f->validate('1')); $this->assertTrue($f->validate('*')); $this->assertFalse($f->validate('*/3,1,1-12')); } /** * @covers \Cron\MinutesField::isSatisfiedBy */ public function testChecksIfSatisfied() { $f = new MinutesField(); $this->assertTrue($f->isSatisfiedBy(new DateTime(), '?')); $this->assertTrue($f->isSatisfiedBy(new DateTimeImmutable(), '?')); } /** * @covers \Cron\MinutesField::increment */ public function testIncrementsDate() { $d = new DateTime('2011-03-15 11:15:00'); $f = new MinutesField(); $f->increment($d); $this->assertSame('2011-03-15 11:16:00', $d->format('Y-m-d H:i:s')); $f->increment($d, true); $this->assertSame('2011-03-15 11:15:00', $d->format('Y-m-d H:i:s')); } /** * @covers \Cron\MinutesField::increment */ public function testIncrementsDateTimeImmutable() { $d = new DateTimeImmutable('2011-03-15 11:15:00'); $f = new MinutesField(); $f->increment($d); $this->assertSame('2011-03-15 11:16:00', $d->format('Y-m-d H:i:s')); } /** * Various bad syntaxes that are reported to work, but shouldn't. * * @author Chris Tankersley * @since 2017-08-18 */ public function testBadSyntaxesShouldNotValidate() { $f = new MinutesField(); $this->assertFalse($f->validate('*-1')); $this->assertFalse($f->validate('1-2-3')); $this->assertFalse($f->validate('-1')); } } PK!ޏ ResourceComparatorTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Comparator; use PHPUnit\Framework\TestCase; /** * @covers \SebastianBergmann\Comparator\ResourceComparator * * @uses \SebastianBergmann\Comparator\Comparator * @uses \SebastianBergmann\Comparator\Factory * @uses \SebastianBergmann\Comparator\ComparisonFailure */ final class ResourceComparatorTest extends TestCase { /** * @var ResourceComparator */ private $comparator; protected function setUp(): void { $this->comparator = new ResourceComparator; } public function acceptsSucceedsProvider() { $tmpfile1 = \tmpfile(); $tmpfile2 = \tmpfile(); return [ [$tmpfile1, $tmpfile1], [$tmpfile2, $tmpfile2], [$tmpfile1, $tmpfile2] ]; } public function acceptsFailsProvider() { $tmpfile1 = \tmpfile(); return [ [$tmpfile1, null], [null, $tmpfile1], [null, null] ]; } public function assertEqualsSucceedsProvider() { $tmpfile1 = \tmpfile(); $tmpfile2 = \tmpfile(); return [ [$tmpfile1, $tmpfile1], [$tmpfile2, $tmpfile2] ]; } public function assertEqualsFailsProvider() { $tmpfile1 = \tmpfile(); $tmpfile2 = \tmpfile(); return [ [$tmpfile1, $tmpfile2], [$tmpfile2, $tmpfile1] ]; } /** * @dataProvider acceptsSucceedsProvider */ public function testAcceptsSucceeds($expected, $actual): void { $this->assertTrue( $this->comparator->accepts($expected, $actual) ); } /** * @dataProvider acceptsFailsProvider */ public function testAcceptsFails($expected, $actual): void { $this->assertFalse( $this->comparator->accepts($expected, $actual) ); } /** * @dataProvider assertEqualsSucceedsProvider */ public function testAssertEqualsSucceeds($expected, $actual): void { $exception = null; try { $this->comparator->assertEquals($expected, $actual); } catch (ComparisonFailure $exception) { } $this->assertNull($exception, 'Unexpected ComparisonFailure'); } /** * @dataProvider assertEqualsFailsProvider */ public function testAssertEqualsFails($expected, $actual): void { $this->expectException(ComparisonFailure::class); $this->comparator->assertEquals($expected, $actual); } } PK!?;^^MockObjectComparatorTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Comparator; use PHPUnit\Framework\TestCase; use stdClass; /** * @covers \SebastianBergmann\Comparator\MockObjectComparator * * @uses \SebastianBergmann\Comparator\Comparator * @uses \SebastianBergmann\Comparator\Factory * @uses \SebastianBergmann\Comparator\ComparisonFailure */ final class MockObjectComparatorTest extends TestCase { /** * @var MockObjectComparator */ private $comparator; protected function setUp(): void { $this->comparator = new MockObjectComparator; $this->comparator->setFactory(new Factory); } public function acceptsSucceedsProvider() { $testmock = $this->createMock(TestClass::class); $stdmock = $this->createMock(stdClass::class); return [ [$testmock, $testmock], [$stdmock, $stdmock], [$stdmock, $testmock] ]; } public function acceptsFailsProvider() { $stdmock = $this->createMock(stdClass::class); return [ [$stdmock, null], [null, $stdmock], [null, null] ]; } public function assertEqualsSucceedsProvider() { // cyclic dependencies $book1 = $this->getMockBuilder(Book::class)->setMethods(null)->getMock(); $book1->author = $this->getMockBuilder(Author::class)->setMethods(null)->setConstructorArgs(['Terry Pratchett'])->getMock(); $book1->author->books[] = $book1; $book2 = $this->getMockBuilder(Book::class)->setMethods(null)->getMock(); $book2->author = $this->getMockBuilder(Author::class)->setMethods(null)->setConstructorArgs(['Terry Pratchett'])->getMock(); $book2->author->books[] = $book2; $object1 = $this->getMockBuilder(SampleClass::class)->setMethods(null)->setConstructorArgs([4, 8, 15])->getMock(); $object2 = $this->getMockBuilder(SampleClass::class)->setMethods(null)->setConstructorArgs([4, 8, 15])->getMock(); return [ [$object1, $object1], [$object1, $object2], [$book1, $book1], [$book1, $book2], [ $this->getMockBuilder(Struct::class)->setMethods(null)->setConstructorArgs([2.3])->getMock(), $this->getMockBuilder(Struct::class)->setMethods(null)->setConstructorArgs([2.5])->getMock(), 0.5 ] ]; } public function assertEqualsFailsProvider() { $typeMessage = 'is not instance of expected class'; $equalMessage = 'Failed asserting that two objects are equal.'; // cyclic dependencies $book1 = $this->getMockBuilder(Book::class)->setMethods(null)->getMock(); $book1->author = $this->getMockBuilder(Author::class)->setMethods(null)->setConstructorArgs(['Terry Pratchett'])->getMock(); $book1->author->books[] = $book1; $book2 = $this->getMockBuilder(Book::class)->setMethods(null)->getMock(); $book1->author = $this->getMockBuilder(Author::class)->setMethods(null)->setConstructorArgs(['Terry Pratch'])->getMock(); $book2->author->books[] = $book2; $book3 = $this->getMockBuilder(Book::class)->setMethods(null)->getMock(); $book3->author = 'Terry Pratchett'; $book4 = $this->createMock(stdClass::class); $book4->author = 'Terry Pratchett'; $object1 = $this->getMockBuilder(SampleClass::class)->setMethods(null)->setConstructorArgs([4, 8, 15])->getMock(); $object2 = $this->getMockBuilder(SampleClass::class)->setMethods(null)->setConstructorArgs([16, 23, 42])->getMock(); return [ [ $this->getMockBuilder(SampleClass::class)->setMethods(null)->setConstructorArgs([4, 8, 15])->getMock(), $this->getMockBuilder(SampleClass::class)->setMethods(null)->setConstructorArgs([16, 23, 42])->getMock(), $equalMessage ], [$object1, $object2, $equalMessage], [$book1, $book2, $equalMessage], [$book3, $book4, $typeMessage], [ $this->getMockBuilder(Struct::class)->setMethods(null)->setConstructorArgs([2.3])->getMock(), $this->getMockBuilder(Struct::class)->setMethods(null)->setConstructorArgs([4.2])->getMock(), $equalMessage, 0.5 ] ]; } /** * @dataProvider acceptsSucceedsProvider */ public function testAcceptsSucceeds($expected, $actual): void { $this->assertTrue( $this->comparator->accepts($expected, $actual) ); } /** * @dataProvider acceptsFailsProvider */ public function testAcceptsFails($expected, $actual): void { $this->assertFalse( $this->comparator->accepts($expected, $actual) ); } /** * @dataProvider assertEqualsSucceedsProvider */ public function testAssertEqualsSucceeds($expected, $actual, $delta = 0.0): void { $exception = null; try { $this->comparator->assertEquals($expected, $actual, $delta); } catch (ComparisonFailure $exception) { } $this->assertNull($exception, 'Unexpected ComparisonFailure'); } /** * @dataProvider assertEqualsFailsProvider */ public function testAssertEqualsFails($expected, $actual, $message, $delta = 0.0): void { $this->expectException(ComparisonFailure::class); $this->expectExceptionMessage($message); $this->comparator->assertEquals($expected, $actual, $delta); } } PK!;,ObjectComparatorTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Comparator; use PHPUnit\Framework\TestCase; use stdClass; /** * @covers \SebastianBergmann\Comparator\ObjectComparator * * @uses \SebastianBergmann\Comparator\Comparator * @uses \SebastianBergmann\Comparator\Factory * @uses \SebastianBergmann\Comparator\ComparisonFailure */ final class ObjectComparatorTest extends TestCase { /** * @var ObjectComparator */ private $comparator; protected function setUp(): void { $this->comparator = new ObjectComparator; $this->comparator->setFactory(new Factory); } public function acceptsSucceedsProvider() { return [ [new TestClass, new TestClass], [new stdClass, new stdClass], [new stdClass, new TestClass] ]; } public function acceptsFailsProvider() { return [ [new stdClass, null], [null, new stdClass], [null, null] ]; } public function assertEqualsSucceedsProvider() { // cyclic dependencies $book1 = new Book; $book1->author = new Author('Terry Pratchett'); $book1->author->books[] = $book1; $book2 = new Book; $book2->author = new Author('Terry Pratchett'); $book2->author->books[] = $book2; $object1 = new SampleClass(4, 8, 15); $object2 = new SampleClass(4, 8, 15); return [ [$object1, $object1], [$object1, $object2], [$book1, $book1], [$book1, $book2], [new Struct(2.3), new Struct(2.5), 0.5] ]; } public function assertEqualsFailsProvider() { $typeMessage = 'is not instance of expected class'; $equalMessage = 'Failed asserting that two objects are equal.'; // cyclic dependencies $book1 = new Book; $book1->author = new Author('Terry Pratchett'); $book1->author->books[] = $book1; $book2 = new Book; $book2->author = new Author('Terry Pratch'); $book2->author->books[] = $book2; $book3 = new Book; $book3->author = 'Terry Pratchett'; $book4 = new stdClass; $book4->author = 'Terry Pratchett'; $object1 = new SampleClass(4, 8, 15); $object2 = new SampleClass(16, 23, 42); return [ [new SampleClass(4, 8, 15), new SampleClass(16, 23, 42), $equalMessage], [$object1, $object2, $equalMessage], [$book1, $book2, $equalMessage], [$book3, $book4, $typeMessage], [new Struct(2.3), new Struct(4.2), $equalMessage, 0.5] ]; } /** * @dataProvider acceptsSucceedsProvider */ public function testAcceptsSucceeds($expected, $actual): void { $this->assertTrue( $this->comparator->accepts($expected, $actual) ); } /** * @dataProvider acceptsFailsProvider */ public function testAcceptsFails($expected, $actual): void { $this->assertFalse( $this->comparator->accepts($expected, $actual) ); } /** * @dataProvider assertEqualsSucceedsProvider */ public function testAssertEqualsSucceeds($expected, $actual, $delta = 0.0): void { $exception = null; try { $this->comparator->assertEquals($expected, $actual, $delta); } catch (ComparisonFailure $exception) { } $this->assertNull($exception, 'Unexpected ComparisonFailure'); } /** * @dataProvider assertEqualsFailsProvider */ public function testAssertEqualsFails($expected, $actual, $message, $delta = 0.0): void { $this->expectException(ComparisonFailure::class); $this->expectExceptionMessage($message); $this->comparator->assertEquals($expected, $actual, $delta); } } PK![؛O O NumericComparatorTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Comparator; use PHPUnit\Framework\TestCase; /** * @covers \SebastianBergmann\Comparator\NumericComparator * * @uses \SebastianBergmann\Comparator\Comparator * @uses \SebastianBergmann\Comparator\Factory * @uses \SebastianBergmann\Comparator\ComparisonFailure */ final class NumericComparatorTest extends TestCase { /** * @var NumericComparator */ private $comparator; protected function setUp(): void { $this->comparator = new NumericComparator; } public function acceptsSucceedsProvider() { return [ [5, 10], [8, '0'], ['10', 0], [0x74c3b00c, 42], [0755, 0777] ]; } public function acceptsFailsProvider() { return [ ['5', '10'], [8, 5.0], [5.0, 8], [10, null], [false, 12] ]; } public function assertEqualsSucceedsProvider() { return [ [1337, 1337], ['1337', 1337], [0x539, 1337], [02471, 1337], [1337, 1338, 1], ['1337', 1340, 5], ]; } public function assertEqualsFailsProvider() { return [ [1337, 1338], ['1338', 1337], [0x539, 1338], [1337, 1339, 1], ['1337', 1340, 2], ]; } /** * @dataProvider acceptsSucceedsProvider */ public function testAcceptsSucceeds($expected, $actual): void { $this->assertTrue( $this->comparator->accepts($expected, $actual) ); } /** * @dataProvider acceptsFailsProvider */ public function testAcceptsFails($expected, $actual): void { $this->assertFalse( $this->comparator->accepts($expected, $actual) ); } /** * @dataProvider assertEqualsSucceedsProvider */ public function testAssertEqualsSucceeds($expected, $actual, $delta = 0.0): void { $exception = null; try { $this->comparator->assertEquals($expected, $actual, $delta); } catch (ComparisonFailure $exception) { } $this->assertNull($exception, 'Unexpected ComparisonFailure'); } /** * @dataProvider assertEqualsFailsProvider */ public function testAssertEqualsFails($expected, $actual, $delta = 0.0): void { $this->expectException(ComparisonFailure::class); $this->expectExceptionMessage('matches expected'); $this->comparator->assertEquals($expected, $actual, $delta); } } PK!hArrayComparatorTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Comparator; use PHPUnit\Framework\TestCase; /** * @covers \SebastianBergmann\Comparator\ArrayComparator * * @uses \SebastianBergmann\Comparator\Comparator * @uses \SebastianBergmann\Comparator\Factory * @uses \SebastianBergmann\Comparator\ComparisonFailure */ final class ArrayComparatorTest extends TestCase { /** * @var ArrayComparator */ private $comparator; protected function setUp(): void { $this->comparator = new ArrayComparator; $this->comparator->setFactory(new Factory); } public function acceptsFailsProvider() { return [ [[], null], [null, []], [null, null] ]; } public function assertEqualsSucceedsProvider() { return [ [ ['a' => 1, 'b' => 2], ['b' => 2, 'a' => 1] ], [ [1], ['1'] ], [ [3, 2, 1], [2, 3, 1], 0, true ], [ [2.3], [2.5], 0.5 ], [ [[2.3]], [[2.5]], 0.5 ], [ [new Struct(2.3)], [new Struct(2.5)], 0.5 ], ]; } public function assertEqualsFailsProvider() { return [ [ [], [0 => 1] ], [ [0 => 1], [] ], [ [0 => null], [] ], [ [0 => 1, 1 => 2], [0 => 1, 1 => 3] ], [ ['a', 'b' => [1, 2]], ['a', 'b' => [2, 1]] ], [ [2.3], [4.2], 0.5 ], [ [[2.3]], [[4.2]], 0.5 ], [ [new Struct(2.3)], [new Struct(4.2)], 0.5 ] ]; } public function testAcceptsSucceeds(): void { $this->assertTrue( $this->comparator->accepts([], []) ); } /** * @dataProvider acceptsFailsProvider */ public function testAcceptsFails($expected, $actual): void { $this->assertFalse( $this->comparator->accepts($expected, $actual) ); } /** * @dataProvider assertEqualsSucceedsProvider */ public function testAssertEqualsSucceeds($expected, $actual, $delta = 0.0, $canonicalize = false): void { $exception = null; try { $this->comparator->assertEquals($expected, $actual, $delta, $canonicalize); } catch (ComparisonFailure $exception) { } $this->assertNull($exception, 'Unexpected ComparisonFailure'); } /** * @dataProvider assertEqualsFailsProvider */ public function testAssertEqualsFails($expected, $actual, $delta = 0.0, $canonicalize = false): void { $this->expectException(ComparisonFailure::class); $this->expectExceptionMessage('Failed asserting that two arrays are equal'); $this->comparator->assertEquals($expected, $actual, $delta, $canonicalize); } } PK! DoubleComparatorTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Comparator; use PHPUnit\Framework\TestCase; /** * @covers \SebastianBergmann\Comparator\DoubleComparator * * @uses \SebastianBergmann\Comparator\Comparator * @uses \SebastianBergmann\Comparator\Factory * @uses \SebastianBergmann\Comparator\ComparisonFailure */ final class DoubleComparatorTest extends TestCase { /** * @var DoubleComparator */ private $comparator; protected function setUp(): void { $this->comparator = new DoubleComparator; } public function acceptsSucceedsProvider() { return [ [0, 5.0], [5.0, 0], ['5', 4.5], [1.2e3, 7E-10], [3, \acos(8)], [\acos(8), 3], [\acos(8), \acos(8)] ]; } public function acceptsFailsProvider() { return [ [5, 5], ['4.5', 5], [0x539, 02471], [5.0, false], [null, 5.0] ]; } public function assertEqualsSucceedsProvider() { return [ [2.3, 2.3], ['2.3', 2.3], [5.0, 5], [5, 5.0], [5.0, '5'], [1.2e3, 1200], [2.3, 2.5, 0.5], [3, 3.05, 0.05], [1.2e3, 1201, 1], [(string) (1 / 3), 1 - 2 / 3], [1 / 3, (string) (1 - 2 / 3)] ]; } public function assertEqualsFailsProvider() { return [ [2.3, 4.2], ['2.3', 4.2], [5.0, '4'], [5.0, 6], [1.2e3, 1201], [2.3, 2.5, 0.2], [3, 3.05, 0.04], [3, \acos(8)], [\acos(8), 3], [\acos(8), \acos(8)] ]; } /** * @dataProvider acceptsSucceedsProvider */ public function testAcceptsSucceeds($expected, $actual): void { $this->assertTrue( $this->comparator->accepts($expected, $actual) ); } /** * @dataProvider acceptsFailsProvider */ public function testAcceptsFails($expected, $actual): void { $this->assertFalse( $this->comparator->accepts($expected, $actual) ); } /** * @dataProvider assertEqualsSucceedsProvider */ public function testAssertEqualsSucceeds($expected, $actual, $delta = 0.0): void { $exception = null; try { $this->comparator->assertEquals($expected, $actual, $delta); } catch (ComparisonFailure $exception) { } $this->assertNull($exception, 'Unexpected ComparisonFailure'); } /** * @dataProvider assertEqualsFailsProvider */ public function testAssertEqualsFails($expected, $actual, $delta = 0.0): void { $this->expectException(ComparisonFailure::class); $this->expectExceptionMessage('matches expected'); $this->comparator->assertEquals($expected, $actual, $delta); } } PK!`(DOMNodeComparatorTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Comparator; use DOMDocument; use DOMNode; use PHPUnit\Framework\TestCase; /** * @covers \SebastianBergmann\Comparator\DOMNodeComparator * * @uses \SebastianBergmann\Comparator\Comparator * @uses \SebastianBergmann\Comparator\Factory * @uses \SebastianBergmann\Comparator\ComparisonFailure */ final class DOMNodeComparatorTest extends TestCase { /** * @var DOMNodeComparator */ private $comparator; protected function setUp(): void { $this->comparator = new DOMNodeComparator; } public function acceptsSucceedsProvider() { $document = new DOMDocument; $node = new DOMNode; return [ [$document, $document], [$node, $node], [$document, $node], [$node, $document] ]; } public function acceptsFailsProvider() { $document = new DOMDocument; return [ [$document, null], [null, $document], [null, null] ]; } public function assertEqualsSucceedsProvider() { return [ [ $this->createDOMDocument(''), $this->createDOMDocument('') ], [ $this->createDOMDocument(''), $this->createDOMDocument('') ], [ $this->createDOMDocument(''), $this->createDOMDocument('') ], [ $this->createDOMDocument("\n \n"), $this->createDOMDocument('') ], [ $this->createDOMDocument(''), $this->createDOMDocument(''), $ignoreCase = true ], [ $this->createDOMDocument(""), $this->createDOMDocument(""), ], ]; } public function assertEqualsFailsProvider() { return [ [ $this->createDOMDocument(''), $this->createDOMDocument('') ], [ $this->createDOMDocument(''), $this->createDOMDocument('') ], [ $this->createDOMDocument(' bar '), $this->createDOMDocument('') ], [ $this->createDOMDocument(''), $this->createDOMDocument('') ], [ $this->createDOMDocument(' bar '), $this->createDOMDocument(' bir ') ], [ $this->createDOMDocument(''), $this->createDOMDocument('') ], [ $this->createDOMDocument(' bar '), $this->createDOMDocument(' BAR ') ] ]; } /** * @dataProvider acceptsSucceedsProvider */ public function testAcceptsSucceeds($expected, $actual): void { $this->assertTrue( $this->comparator->accepts($expected, $actual) ); } /** * @dataProvider acceptsFailsProvider */ public function testAcceptsFails($expected, $actual): void { $this->assertFalse( $this->comparator->accepts($expected, $actual) ); } /** * @dataProvider assertEqualsSucceedsProvider */ public function testAssertEqualsSucceeds($expected, $actual, $ignoreCase = false): void { $exception = null; try { $delta = 0.0; $canonicalize = false; $this->comparator->assertEquals($expected, $actual, $delta, $canonicalize, $ignoreCase); } catch (ComparisonFailure $exception) { } $this->assertNull($exception, 'Unexpected ComparisonFailure'); } /** * @dataProvider assertEqualsFailsProvider */ public function testAssertEqualsFails($expected, $actual): void { $this->expectException(ComparisonFailure::class); $this->expectExceptionMessage('Failed asserting that two DOM'); $this->comparator->assertEquals($expected, $actual); } private function createDOMDocument($content) { $document = new DOMDocument; $document->preserveWhiteSpace = false; $document->loadXML($content); return $document; } } PK! TypeComparatorTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Comparator; use PHPUnit\Framework\TestCase; use stdClass; /** * @covers \SebastianBergmann\Comparator\TypeComparator * * @uses \SebastianBergmann\Comparator\Comparator * @uses \SebastianBergmann\Comparator\Factory * @uses \SebastianBergmann\Comparator\ComparisonFailure */ final class TypeComparatorTest extends TestCase { /** * @var TypeComparator */ private $comparator; protected function setUp(): void { $this->comparator = new TypeComparator; } public function acceptsSucceedsProvider() { return [ [true, 1], [false, [1]], [null, new stdClass], [1.0, 5], ['', ''] ]; } public function assertEqualsSucceedsProvider() { return [ [true, true], [true, false], [false, false], [null, null], [new stdClass, new stdClass], [0, 0], [1.0, 2.0], ['hello', 'world'], ['', ''], [[], [1, 2, 3]] ]; } public function assertEqualsFailsProvider() { return [ [true, null], [null, false], [1.0, 0], [new stdClass, []], ['1', 1] ]; } /** * @dataProvider acceptsSucceedsProvider */ public function testAcceptsSucceeds($expected, $actual): void { $this->assertTrue( $this->comparator->accepts($expected, $actual) ); } /** * @dataProvider assertEqualsSucceedsProvider */ public function testAssertEqualsSucceeds($expected, $actual): void { $exception = null; try { $this->comparator->assertEquals($expected, $actual); } catch (ComparisonFailure $exception) { } $this->assertNull($exception, 'Unexpected ComparisonFailure'); } /** * @dataProvider assertEqualsFailsProvider */ public function testAssertEqualsFails($expected, $actual): void { $this->expectException(ComparisonFailure::class); $this->expectExceptionMessage('does not match expected type'); $this->comparator->assertEquals($expected, $actual); } } PK!P[[ExceptionComparatorTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Comparator; use Exception; use PHPUnit\Framework\TestCase; use RuntimeException; /** * @covers \SebastianBergmann\Comparator\ExceptionComparator * * @uses \SebastianBergmann\Comparator\Comparator * @uses \SebastianBergmann\Comparator\Factory * @uses \SebastianBergmann\Comparator\ComparisonFailure */ final class ExceptionComparatorTest extends TestCase { /** * @var ExceptionComparator */ private $comparator; protected function setUp(): void { $this->comparator = new ExceptionComparator; $this->comparator->setFactory(new Factory); } public function acceptsSucceedsProvider() { return [ [new Exception, new Exception], [new RuntimeException, new RuntimeException], [new Exception, new RuntimeException] ]; } public function acceptsFailsProvider() { return [ [new Exception, null], [null, new Exception], [null, null] ]; } public function assertEqualsSucceedsProvider() { $exception1 = new Exception; $exception2 = new Exception; $exception3 = new RuntimeException('Error', 100); $exception4 = new RuntimeException('Error', 100); return [ [$exception1, $exception1], [$exception1, $exception2], [$exception3, $exception3], [$exception3, $exception4] ]; } public function assertEqualsFailsProvider() { $typeMessage = 'not instance of expected class'; $equalMessage = 'Failed asserting that two objects are equal.'; $exception1 = new Exception('Error', 100); $exception2 = new Exception('Error', 101); $exception3 = new Exception('Errors', 101); $exception4 = new RuntimeException('Error', 100); $exception5 = new RuntimeException('Error', 101); return [ [$exception1, $exception2, $equalMessage], [$exception1, $exception3, $equalMessage], [$exception1, $exception4, $typeMessage], [$exception2, $exception3, $equalMessage], [$exception4, $exception5, $equalMessage] ]; } /** * @dataProvider acceptsSucceedsProvider */ public function testAcceptsSucceeds($expected, $actual): void { $this->assertTrue( $this->comparator->accepts($expected, $actual) ); } /** * @dataProvider acceptsFailsProvider */ public function testAcceptsFails($expected, $actual): void { $this->assertFalse( $this->comparator->accepts($expected, $actual) ); } /** * @dataProvider assertEqualsSucceedsProvider */ public function testAssertEqualsSucceeds($expected, $actual): void { $exception = null; try { $this->comparator->assertEquals($expected, $actual); } catch (ComparisonFailure $exception) { } $this->assertNull($exception, 'Unexpected ComparisonFailure'); } /** * @dataProvider assertEqualsFailsProvider */ public function testAssertEqualsFails($expected, $actual, $message): void { $this->expectException(ComparisonFailure::class); $this->expectExceptionMessage($message); $this->comparator->assertEquals($expected, $actual); } } PK!!ComparisonFailureTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Comparator; use PHPUnit\Framework\TestCase; /** * @covers \SebastianBergmann\Comparator\ComparisonFailure * * @uses \SebastianBergmann\Comparator\Factory */ final class ComparisonFailureTest extends TestCase { public function testComparisonFailure(): void { $actual = "\nB\n"; $expected = "\nA\n"; $message = 'Test message'; $failure = new ComparisonFailure( $expected, $actual, '|' . $expected, '|' . $actual, false, $message ); $this->assertSame($actual, $failure->getActual()); $this->assertSame($expected, $failure->getExpected()); $this->assertSame('|' . $actual, $failure->getActualAsString()); $this->assertSame('|' . $expected, $failure->getExpectedAsString()); $diff = ' --- Expected +++ Actual @@ @@ | -A +B '; $this->assertSame($diff, $failure->getDiff()); $this->assertSame($message . $diff, $failure->toString()); } public function testDiffNotPossible(): void { $failure = new ComparisonFailure('a', 'b', false, false, true, 'test'); $this->assertSame('', $failure->getDiff()); $this->assertSame('test', $failure->toString()); } } PK!o:UUFactoryTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Comparator; use PHPUnit\Framework\TestCase; /** * @covers \SebastianBergmann\Comparator\Factory * * @uses \SebastianBergmann\Comparator\Comparator * @uses \SebastianBergmann\Comparator\Factory * @uses \SebastianBergmann\Comparator\ComparisonFailure */ final class FactoryTest extends TestCase { public function instanceProvider() { $tmpfile = \tmpfile(); return [ [null, null, 'SebastianBergmann\\Comparator\\ScalarComparator'], [null, true, 'SebastianBergmann\\Comparator\\ScalarComparator'], [true, null, 'SebastianBergmann\\Comparator\\ScalarComparator'], [true, true, 'SebastianBergmann\\Comparator\\ScalarComparator'], [false, false, 'SebastianBergmann\\Comparator\\ScalarComparator'], [true, false, 'SebastianBergmann\\Comparator\\ScalarComparator'], [false, true, 'SebastianBergmann\\Comparator\\ScalarComparator'], ['', '', 'SebastianBergmann\\Comparator\\ScalarComparator'], ['0', '0', 'SebastianBergmann\\Comparator\\ScalarComparator'], ['0', 0, 'SebastianBergmann\\Comparator\\NumericComparator'], [0, '0', 'SebastianBergmann\\Comparator\\NumericComparator'], [0, 0, 'SebastianBergmann\\Comparator\\NumericComparator'], [1.0, 0, 'SebastianBergmann\\Comparator\\DoubleComparator'], [0, 1.0, 'SebastianBergmann\\Comparator\\DoubleComparator'], [1.0, 1.0, 'SebastianBergmann\\Comparator\\DoubleComparator'], [[1], [1], 'SebastianBergmann\\Comparator\\ArrayComparator'], [$tmpfile, $tmpfile, 'SebastianBergmann\\Comparator\\ResourceComparator'], [new \stdClass, new \stdClass, 'SebastianBergmann\\Comparator\\ObjectComparator'], [new \DateTime, new \DateTime, 'SebastianBergmann\\Comparator\\DateTimeComparator'], [new \SplObjectStorage, new \SplObjectStorage, 'SebastianBergmann\\Comparator\\SplObjectStorageComparator'], [new \Exception, new \Exception, 'SebastianBergmann\\Comparator\\ExceptionComparator'], [new \DOMDocument, new \DOMDocument, 'SebastianBergmann\\Comparator\\DOMNodeComparator'], // mixed types [$tmpfile, [1], 'SebastianBergmann\\Comparator\\TypeComparator'], [[1], $tmpfile, 'SebastianBergmann\\Comparator\\TypeComparator'], [$tmpfile, '1', 'SebastianBergmann\\Comparator\\TypeComparator'], ['1', $tmpfile, 'SebastianBergmann\\Comparator\\TypeComparator'], [$tmpfile, new \stdClass, 'SebastianBergmann\\Comparator\\TypeComparator'], [new \stdClass, $tmpfile, 'SebastianBergmann\\Comparator\\TypeComparator'], [new \stdClass, [1], 'SebastianBergmann\\Comparator\\TypeComparator'], [[1], new \stdClass, 'SebastianBergmann\\Comparator\\TypeComparator'], [new \stdClass, '1', 'SebastianBergmann\\Comparator\\TypeComparator'], ['1', new \stdClass, 'SebastianBergmann\\Comparator\\TypeComparator'], [new ClassWithToString, '1', 'SebastianBergmann\\Comparator\\ScalarComparator'], ['1', new ClassWithToString, 'SebastianBergmann\\Comparator\\ScalarComparator'], [1.0, new \stdClass, 'SebastianBergmann\\Comparator\\TypeComparator'], [new \stdClass, 1.0, 'SebastianBergmann\\Comparator\\TypeComparator'], [1.0, [1], 'SebastianBergmann\\Comparator\\TypeComparator'], [[1], 1.0, 'SebastianBergmann\\Comparator\\TypeComparator'], ]; } /** * @dataProvider instanceProvider */ public function testGetComparatorFor($a, $b, $expected): void { $factory = new Factory; $actual = $factory->getComparatorFor($a, $b); $this->assertInstanceOf($expected, $actual); } public function testRegister(): void { $comparator = new TestClassComparator; $factory = new Factory; $factory->register($comparator); $a = new TestClass; $b = new TestClass; $expected = 'SebastianBergmann\\Comparator\\TestClassComparator'; $actual = $factory->getComparatorFor($a, $b); $factory->unregister($comparator); $this->assertInstanceOf($expected, $actual); } public function testUnregister(): void { $comparator = new TestClassComparator; $factory = new Factory; $factory->register($comparator); $factory->unregister($comparator); $a = new TestClass; $b = new TestClass; $expected = 'SebastianBergmann\\Comparator\\ObjectComparator'; $actual = $factory->getComparatorFor($a, $b); $this->assertInstanceOf($expected, $actual); } public function testIsSingleton(): void { $f = Factory::getInstance(); $this->assertSame($f, Factory::getInstance()); } } PK!U_fixture/ClassWithToString.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Comparator; class ClassWithToString { public function __toString() { return 'string representation'; } } PK!ȧ_fixture/Book.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Comparator; /** * A book. */ class Book { // the order of properties is important for testing the cycle! public $author; } PK!!QQ _fixture/TestClassComparator.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Comparator; class TestClassComparator extends ObjectComparator { } PK!q\_fixture/Struct.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Comparator; /** * A struct. */ class Struct { public $var; public function __construct($var) { $this->var = $var; } } PK!#.._fixture/TestClass.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Comparator; class TestClass { } PK!_fixture/SampleClass.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Comparator; /** * A sample class. */ class SampleClass { public $a; protected $b; protected $c; public function __construct($a, $b, $c) { $this->a = $a; $this->b = $b; $this->c = $c; } } PK!#06_fixture/Author.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Comparator; /** * An author. */ class Author { // the order of properties is important for testing the cycle! public $books = []; private $name = ''; public function __construct($name) { $this->name = $name; } } PK!0f!!ScalarComparatorTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Comparator; use PHPUnit\Framework\TestCase; /** * @covers \SebastianBergmann\Comparator\ScalarComparator * * @uses \SebastianBergmann\Comparator\Comparator * @uses \SebastianBergmann\Comparator\Factory * @uses \SebastianBergmann\Comparator\ComparisonFailure */ final class ScalarComparatorTest extends TestCase { /** * @var ScalarComparator */ private $comparator; protected function setUp(): void { $this->comparator = new ScalarComparator; } public function acceptsSucceedsProvider() { return [ ['string', 'string'], [new ClassWithToString, 'string'], ['string', new ClassWithToString], ['string', null], [false, 'string'], [false, true], [null, false], [null, null], ['10', 10], ['', false], ['1', true], [1, true], [0, false], [0.1, '0.1'] ]; } public function acceptsFailsProvider() { return [ [[], []], ['string', []], [new ClassWithToString, new ClassWithToString], [false, new ClassWithToString], [\tmpfile(), \tmpfile()] ]; } public function assertEqualsSucceedsProvider() { return [ ['string', 'string'], [new ClassWithToString, new ClassWithToString], ['string representation', new ClassWithToString], [new ClassWithToString, 'string representation'], ['string', 'STRING', true], ['STRING', 'string', true], ['String Representation', new ClassWithToString, true], [new ClassWithToString, 'String Representation', true], ['10', 10], ['', false], ['1', true], [1, true], [0, false], [0.1, '0.1'], [false, null], [false, false], [true, true], [null, null] ]; } public function assertEqualsFailsProvider() { $stringException = 'Failed asserting that two strings are equal.'; $otherException = 'matches expected'; return [ ['string', 'other string', $stringException], ['string', 'STRING', $stringException], ['STRING', 'string', $stringException], ['string', 'other string', $stringException], // https://github.com/sebastianbergmann/phpunit/issues/1023 ['9E6666666', '9E7777777', $stringException], [new ClassWithToString, 'does not match', $otherException], ['does not match', new ClassWithToString, $otherException], [0, 'Foobar', $otherException], ['Foobar', 0, $otherException], ['10', 25, $otherException], ['1', false, $otherException], ['', true, $otherException], [false, true, $otherException], [true, false, $otherException], [null, true, $otherException], [0, true, $otherException], ['0', '0.0', $stringException], ['0.', '0.0', $stringException], ['0e1', '0e2', $stringException], ["\n\n\n0.0", ' 0.', $stringException], ['0.0', '25e-10000', $stringException], ]; } /** * @dataProvider acceptsSucceedsProvider */ public function testAcceptsSucceeds($expected, $actual): void { $this->assertTrue( $this->comparator->accepts($expected, $actual) ); } /** * @dataProvider acceptsFailsProvider */ public function testAcceptsFails($expected, $actual): void { $this->assertFalse( $this->comparator->accepts($expected, $actual) ); } /** * @dataProvider assertEqualsSucceedsProvider */ public function testAssertEqualsSucceeds($expected, $actual, $ignoreCase = false): void { $exception = null; try { $this->comparator->assertEquals($expected, $actual, 0.0, false, $ignoreCase); } catch (ComparisonFailure $exception) { } $this->assertNull($exception, 'Unexpected ComparisonFailure'); } /** * @dataProvider assertEqualsFailsProvider */ public function testAssertEqualsFails($expected, $actual, $message): void { $this->expectException(ComparisonFailure::class); $this->expectExceptionMessage($message); $this->comparator->assertEquals($expected, $actual); } } PK!DC]]DateTimeComparatorTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Comparator; use DateTime; use DateTimeImmutable; use DateTimeZone; use PHPUnit\Framework\TestCase; /** * @covers \SebastianBergmann\Comparator\DateTimeComparator * * @uses \SebastianBergmann\Comparator\Comparator * @uses \SebastianBergmann\Comparator\Factory * @uses \SebastianBergmann\Comparator\ComparisonFailure */ final class DateTimeComparatorTest extends TestCase { /** * @var DateTimeComparator */ private $comparator; protected function setUp(): void { $this->comparator = new DateTimeComparator; } public function acceptsFailsProvider() { $datetime = new DateTime; return [ [$datetime, null], [null, $datetime], [null, null] ]; } public function assertEqualsSucceedsProvider() { return [ [ new DateTime('2013-03-29 04:13:35', new DateTimeZone('America/New_York')), new DateTime('2013-03-29 04:13:25', new DateTimeZone('America/New_York')), 10 ], [ new DateTime('2013-03-29 04:13:35', new DateTimeZone('America/New_York')), new DateTime('2013-03-29 04:14:40', new DateTimeZone('America/New_York')), 65 ], [ new DateTime('2013-03-29', new DateTimeZone('America/New_York')), new DateTime('2013-03-29', new DateTimeZone('America/New_York')) ], [ new DateTime('2013-03-29 04:13:35', new DateTimeZone('America/New_York')), new DateTime('2013-03-29 03:13:35', new DateTimeZone('America/Chicago')) ], [ new DateTime('2013-03-29 04:13:35', new DateTimeZone('America/New_York')), new DateTime('2013-03-29 03:13:49', new DateTimeZone('America/Chicago')), 15 ], [ new DateTime('2013-03-30', new DateTimeZone('America/New_York')), new DateTime('2013-03-29 23:00:00', new DateTimeZone('America/Chicago')) ], [ new DateTime('2013-03-30', new DateTimeZone('America/New_York')), new DateTime('2013-03-29 23:01:30', new DateTimeZone('America/Chicago')), 100 ], [ new DateTime('@1364616000'), new DateTime('2013-03-29 23:00:00', new DateTimeZone('America/Chicago')) ], [ new DateTime('2013-03-29T05:13:35-0500'), new DateTime('2013-03-29T04:13:35-0600') ], [ new DateTimeImmutable('2013-03-30', new DateTimeZone('America/New_York')), new DateTimeImmutable('2013-03-29 23:01:30', new DateTimeZone('America/Chicago')), 100 ], [ new DateTimeImmutable('2013-03-30 12:00:00', new DateTimeZone('UTC')), new DateTimeImmutable('2013-03-30 12:00:00.5', new DateTimeZone('UTC')), 0.5 ], ]; } public function assertEqualsFailsProvider() { return [ [ new DateTime('2013-03-29 04:13:35', new DateTimeZone('America/New_York')), new DateTime('2013-03-29 03:13:35', new DateTimeZone('America/New_York')) ], [ new DateTime('2013-03-29 04:13:35', new DateTimeZone('America/New_York')), new DateTime('2013-03-29 03:13:35', new DateTimeZone('America/New_York')), 3500 ], [ new DateTime('2013-03-29 04:13:35', new DateTimeZone('America/New_York')), new DateTime('2013-03-29 05:13:35', new DateTimeZone('America/New_York')), 3500 ], [ new DateTime('2013-03-29', new DateTimeZone('America/New_York')), new DateTime('2013-03-30', new DateTimeZone('America/New_York')) ], [ new DateTime('2013-03-29', new DateTimeZone('America/New_York')), new DateTime('2013-03-30', new DateTimeZone('America/New_York')), 43200 ], [ new DateTime('2013-03-29 04:13:35', new DateTimeZone('America/New_York')), new DateTime('2013-03-29 04:13:35', new DateTimeZone('America/Chicago')), ], [ new DateTime('2013-03-29 04:13:35', new DateTimeZone('America/New_York')), new DateTime('2013-03-29 04:13:35', new DateTimeZone('America/Chicago')), 3500 ], [ new DateTime('2013-03-30', new DateTimeZone('America/New_York')), new DateTime('2013-03-30', new DateTimeZone('America/Chicago')) ], [ new DateTime('2013-03-29T05:13:35-0600'), new DateTime('2013-03-29T04:13:35-0600') ], [ new DateTime('2013-03-29T05:13:35-0600'), new DateTime('2013-03-29T05:13:35-0500') ], ]; } public function testAcceptsSucceeds(): void { $this->assertTrue( $this->comparator->accepts( new DateTime, new DateTime ) ); } /** * @dataProvider acceptsFailsProvider */ public function testAcceptsFails($expected, $actual): void { $this->assertFalse( $this->comparator->accepts($expected, $actual) ); } /** * @dataProvider assertEqualsSucceedsProvider */ public function testAssertEqualsSucceeds($expected, $actual, $delta = 0.0): void { $exception = null; try { $this->comparator->assertEquals($expected, $actual, $delta); } catch (ComparisonFailure $exception) { } $this->assertNull($exception, 'Unexpected ComparisonFailure'); } /** * @dataProvider assertEqualsFailsProvider */ public function testAssertEqualsFails($expected, $actual, $delta = 0.0): void { $this->expectException(ComparisonFailure::class); $this->expectExceptionMessage('Failed asserting that two DateTime objects are equal.'); $this->comparator->assertEquals($expected, $actual, $delta); } public function testAcceptsDateTimeInterface(): void { $this->assertTrue($this->comparator->accepts(new DateTime, new DateTimeImmutable)); } public function testSupportsDateTimeInterface(): void { $this->assertNull( $this->comparator->assertEquals( new DateTime('2013-03-29 04:13:35', new DateTimeZone('America/New_York')), new DateTimeImmutable('2013-03-29 04:13:35', new DateTimeZone('America/New_York')) ) ); } } PK!Zx"SplObjectStorageComparatorTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\Comparator; use PHPUnit\Framework\TestCase; use SplObjectStorage; use stdClass; /** * @covers \SebastianBergmann\Comparator\SplObjectStorageComparator * * @uses \SebastianBergmann\Comparator\Comparator * @uses \SebastianBergmann\Comparator\Factory * @uses \SebastianBergmann\Comparator\ComparisonFailure */ final class SplObjectStorageComparatorTest extends TestCase { /** * @var SplObjectStorageComparator */ private $comparator; protected function setUp(): void { $this->comparator = new SplObjectStorageComparator; } public function acceptsFailsProvider() { return [ [new SplObjectStorage, new stdClass], [new stdClass, new SplObjectStorage], [new stdClass, new stdClass] ]; } public function assertEqualsSucceedsProvider() { $object1 = new stdClass(); $object2 = new stdClass(); $storage1 = new SplObjectStorage(); $storage2 = new SplObjectStorage(); $storage3 = new SplObjectStorage(); $storage3->attach($object1); $storage3->attach($object2); $storage4 = new SplObjectStorage(); $storage4->attach($object2); $storage4->attach($object1); return [ [$storage1, $storage1], [$storage1, $storage2], [$storage3, $storage3], [$storage3, $storage4] ]; } public function assertEqualsFailsProvider() { $object1 = new stdClass; $object2 = new stdClass; $storage1 = new SplObjectStorage; $storage2 = new SplObjectStorage; $storage2->attach($object1); $storage3 = new SplObjectStorage; $storage3->attach($object2); $storage3->attach($object1); return [ [$storage1, $storage2], [$storage1, $storage3], [$storage2, $storage3], ]; } public function testAcceptsSucceeds(): void { $this->assertTrue( $this->comparator->accepts( new SplObjectStorage, new SplObjectStorage ) ); } /** * @dataProvider acceptsFailsProvider */ public function testAcceptsFails($expected, $actual): void { $this->assertFalse( $this->comparator->accepts($expected, $actual) ); } /** * @dataProvider assertEqualsSucceedsProvider */ public function testAssertEqualsSucceeds($expected, $actual): void { $exception = null; try { $this->comparator->assertEquals($expected, $actual); } catch (ComparisonFailure $exception) { } $this->assertNull($exception, 'Unexpected ComparisonFailure'); } /** * @dataProvider assertEqualsFailsProvider */ public function testAssertEqualsFails($expected, $actual): void { $this->expectException(ComparisonFailure::class); $this->expectExceptionMessage('Failed asserting that two objects are equal.'); $this->comparator->assertEquals($expected, $actual); } public function testAssertEqualsFails2(): void { $this->expectException(ComparisonFailure::class); $this->expectExceptionMessage('Failed asserting that two objects are equal.'); $t = new SplObjectStorage(); $t->attach(new \stdClass()); $this->comparator->assertEquals($t, new \SplObjectStorage()); } } PK!CbResourceOperationsTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\ResourceOperations; use PHPUnit\Framework\TestCase; /** * @covers \SebastianBergmann\ResourceOperations\ResourceOperations */ final class ResourceOperationsTest extends TestCase { public function testGetFunctions(): void { $functions = ResourceOperations::getFunctions(); $this->assertInternalType('array', $functions); $this->assertContains('fopen', $functions); } } PK!+ s# # EnumeratorTest.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\ObjectEnumerator; use SebastianBergmann\ObjectEnumerator\Fixtures\ExceptionThrower; use PHPUnit\Framework\TestCase; /** * @covers SebastianBergmann\ObjectEnumerator\Enumerator */ class EnumeratorTest extends TestCase { /** * @var Enumerator */ private $enumerator; protected function setUp() { $this->enumerator = new Enumerator; } public function testEnumeratesSingleObject() { $a = new \stdClass; $objects = $this->enumerator->enumerate($a); $this->assertCount(1, $objects); $this->assertSame($a, $objects[0]); } public function testEnumeratesArrayWithSingleObject() { $a = new \stdClass; $objects = $this->enumerator->enumerate([$a]); $this->assertCount(1, $objects); $this->assertSame($a, $objects[0]); } public function testEnumeratesArrayWithTwoReferencesToTheSameObject() { $a = new \stdClass; $objects = $this->enumerator->enumerate([$a, $a]); $this->assertCount(1, $objects); $this->assertSame($a, $objects[0]); } public function testEnumeratesArrayOfObjects() { $a = new \stdClass; $b = new \stdClass; $objects = $this->enumerator->enumerate([$a, $b, null]); $this->assertCount(2, $objects); $this->assertSame($a, $objects[0]); $this->assertSame($b, $objects[1]); } public function testEnumeratesObjectWithAggregatedObject() { $a = new \stdClass; $b = new \stdClass; $a->b = $b; $a->c = null; $objects = $this->enumerator->enumerate($a); $this->assertCount(2, $objects); $this->assertSame($a, $objects[0]); $this->assertSame($b, $objects[1]); } public function testEnumeratesObjectWithAggregatedObjectsInArray() { $a = new \stdClass; $b = new \stdClass; $a->b = [$b]; $objects = $this->enumerator->enumerate($a); $this->assertCount(2, $objects); $this->assertSame($a, $objects[0]); $this->assertSame($b, $objects[1]); } public function testEnumeratesObjectsWithCyclicReferences() { $a = new \stdClass; $b = new \stdClass; $a->b = $b; $b->a = $a; $objects = $this->enumerator->enumerate([$a, $b]); $this->assertCount(2, $objects); $this->assertSame($a, $objects[0]); $this->assertSame($b, $objects[1]); } public function testEnumeratesClassThatThrowsException() { $thrower = new ExceptionThrower(); $objects = $this->enumerator->enumerate($thrower); $this->assertSame($thrower, $objects[0]); } public function testExceptionIsRaisedForInvalidArgument() { $this->expectException(InvalidArgumentException::class); $this->enumerator->enumerate(null); } public function testExceptionIsRaisedForInvalidArgument2() { $this->expectException(InvalidArgumentException::class); $this->enumerator->enumerate([], ''); } } PK!$I_fixture/ExceptionThrower.phpnu[ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\ObjectEnumerator\Fixtures; use RuntimeException; class ExceptionThrower { private $property; public function __construct() { unset($this->property); } public function __get($property) { throw new RuntimeException; } } PK!e>44CreateTagFromArrayTests.phpnu[PK!C4ReplaceEntitiesTests.phpnu[PK!یu(FApiVersionTests.phpnu[PK!GsHGBug5392Tests.phpnu[PK!4ejjJCreateCDataSectionTests.phpnu[PK!|\5McBug4950Tests.phpnu[PK!YR""5fCreateStartElementTests.phpnu[PK!ܬ${GetDocTypeDeclarationTests.phpnu[PK!GBug21177Tests.phpnu[PK!۩BBug18343Tests.phpnu[PK!ztQReverseEntitiesTests.phpnu[PK!~$[eeoCreateEndElementTests.phpnu[PK!!AbstractUnitTests.phpnu[PK!m4** CreateTagTests.phpnu[PK!Df:vGetXmlDeclarationTests.phpnu[PK!ZtLAttributesToStringTests.phpnu[PK!ݑhIsValidNameTests.phpnu[PK!TTCreateCommentTests.phpnu[PK!rvJRaiseErrorTests.phpnu[PK!`f3##.Mpear/Structures_Graph/tests/BasicGraphTest.phpnu[PK! ;VV50pear/Structures_Graph/tests/TopologicalSorterTest.phpnu[PK!e/pear/Structures_Graph/tests/AcyclicTestTest.phpnu[PK!5htt&g#pear/Structures_Graph/tests/helper.incnu[PK!)1%pear/Console_Getopt/tests/001-getopt.phptnu[PK!'X*pear/Console_Getopt/tests/bug11068.phptnu[PK!'-pear/Console_Getopt/tests/bug10557.phptnu[PK!|EE' 0pear/Console_Getopt/tests/bug13140.phptnu[PK!e>44/5pear/XML_Util/tests/CreateTagFromArrayTests.phpnu[PK!C,jpear/XML_Util/tests/ReplaceEntitiesTests.phpnu[PK!یu'{pear/XML_Util/tests/ApiVersionTests.phpnu[PK!Gs$-}pear/XML_Util/tests/Bug5392Tests.phpnu[PK!4ejj/pear/XML_Util/tests/CreateCDataSectionTests.phpnu[PK!|\5.Ipear/XML_Util/tests/CollapseEmptyTagsTests.phpnu[PK!GG/pear/XML_Util/tests/SplitQualifiedNameTests.phpnu[PK!Yq%Npear/XML_Util/tests/Bug21184Tests.phpnu[PK!>M$epear/XML_Util/tests/Bug4950Tests.phpnu[PK!YR""/pear/XML_Util/tests/CreateStartElementTests.phpnu[PK!ܬ$2pear/XML_Util/tests/GetDocTypeDeclarationTests.phpnu[PK!G%hpear/XML_Util/tests/Bug21177Tests.phpnu[PK!۩%۽pear/XML_Util/tests/Bug18343Tests.phpnu[PK!zt,pear/XML_Util/tests/ReverseEntitiesTests.phpnu[PK!~$[ee-0pear/XML_Util/tests/CreateEndElementTests.phpnu[PK!!)pear/XML_Util/tests/AbstractUnitTests.phpnu[PK!m4**&pear/XML_Util/tests/CreateTagTests.phpnu[PK!Df:.spear/XML_Util/tests/GetXmlDeclarationTests.phpnu[PK!Zt/]pear/XML_Util/tests/AttributesToStringTests.phpnu[PK!ݑh(pear/XML_Util/tests/IsValidNameTests.phpnu[PK!TT*%pear/XML_Util/tests/CreateCommentTests.phpnu[PK!rv''pear/XML_Util/tests/RaiseErrorTests.phpnu[PK! )__init__.pynu[PK!wӷKKtest_windows.pynu[PK![2[2<test_unicode.pynu[PK!XAmm %otest_aix.pynu[PK!,g ̀__main__.pynu[PK!1 33 ҋtest_linux.pynu[PK!%% test_osx.pynu[PK! ltest_sunos.pynu[PK!nrXrX/__pycache__/test_contracts.cpython-36.opt-1.pycnu[PK! DD#C__pycache__/test_bsd.cpython-36.pycnu[PK!Zaa,Έ__pycache__/test_system.cpython-36.opt-1.pycnu[PK!&g[*$__pycache__/test_misc.cpython-36.opt-1.pycnu[PK!++-jl__pycache__/test_unicode.cpython-36.opt-1.pycnu[PK!oo'K__pycache__/test_windows.cpython-36.pycnu[PK!+__pycache__/test_linux.cpython-36.opt-1.pycnu[PK!V% #__pycache__/test_aix.cpython-36.pycnu[PK!//bfixtures/serialized_diff.binnu[PK!C6sfixtures/UnifiedDiffAssertTraitIntegrationTest/1_a.txtnu[PK!2##6}sfixtures/UnifiedDiffAssertTraitIntegrationTest/2_b.txtnu[PK!&/EE6tfixtures/UnifiedDiffAssertTraitIntegrationTest/2_a.txtnu[PK!6tfixtures/UnifiedDiffAssertTraitIntegrationTest/1_b.txtnu[PK!@k鐚ufixtures/patch2.txtnu[PK!Y0MÒ vChunkTest.phpnu[PK!..}DifferTest.phpnu[PK!8 ParserTest.phpnu[PK!uu IDiffTest.phpnu[PK!$yy#TimeEfficientImplementationTest.phpnu[PK!kUtils/FileUtils.phpnu[PK!d,d,$Utils/UnifiedDiffAssertTraitTest.phpnu[PK!"ڸ++ Utils/UnifiedDiffAssertTrait.phpnu[PK! /%Utils/UnifiedDiffAssertTraitIntegrationTest.phpnu[PK!?澚^^(6Exception/ConfigurationExceptionTest.phpnu[PK!7,8*:Exception/InvalidArgumentExceptionTest.phpnu[PK!x ?LongestCommonSubsequenceTest.phpnu[PK!2otA/UOutput/UnifiedDiffOutputBuilderDataProvider.phpnu[PK!0>kOutput/Integration/UnifiedDiffOutputBuilderIntegrationTest.phpnu[PK!ܫ<'<'D~Output/Integration/StrictUnifiedDiffOutputBuilderIntegrationTest.phpnu[PK!+VDVD-Output/StrictUnifiedDiffOutputBuilderTest.phpnu[PK!z6|dd$GOutput/DiffOnlyOutputBuilderTest.phpnu[PK!(& & 5Output/StrictUnifiedDiffOutputBuilderDataProvider.phpnu[PK!zlV V 'Output/UnifiedDiffOutputBuilderTest.phpnu[PK!R~)))7 Output/AbstractChunkOutputBuilderTest.phpnu[PK! %y%MemoryEfficientImplementationTest.phpnu[PK!NEWhhCron/CronExpressionTest.phpnu[PK!;<<kCron/DayOfMonthFieldTest.phpnu[PK!; ; Cron/HoursFieldTest.phpnu[PK!8uCron/FieldFactoryTest.phpnu[PK!e&C C mCron/MonthFieldTest.phpnu[PK!0|wwCron/DayOfWeekFieldTest.phpnu[PK!OCron/AbstractFieldTest.phpnu[PK!oCron/MinutesFieldTest.phpnu[PK!ޏ ResourceComparatorTest.phpnu[PK!?;^^MockObjectComparatorTest.phpnu[PK!;,ObjectComparatorTest.phpnu[PK![؛O O NumericComparatorTest.phpnu[PK!hArrayComparatorTest.phpnu[PK! *DoubleComparatorTest.phpnu[PK!`(7DOMNodeComparatorTest.phpnu[PK! LTypeComparatorTest.phpnu[PK!P[[3VExceptionComparatorTest.phpnu[PK!!dComparisonFailureTest.phpnu[PK!o:UU)kFactoryTest.phpnu[PK!U_fixture/ClassWithToString.phpnu[PK!ȧ_fixture/Book.phpnu[PK!!QQ j_fixture/TestClassComparator.phpnu[PK!q\ _fixture/Struct.phpnu[PK!#.._fixture/TestClass.phpnu[PK!a_fixture/SampleClass.phpnu[PK!#06_fixture/Author.phpnu[PK!0f!!ScalarComparatorTest.phpnu[PK!DC]]YDateTimeComparatorTest.phpnu[PK!Zx"SplObjectStorageComparatorTest.phpnu[PK!CbResourceOperationsTest.phpnu[PK!+ s# # EnumeratorTest.phpnu[PK!$Ie_fixture/ExceptionThrower.phpnu[PK