Kaydet (Commit) a40c6ccc authored tarafından Suleyman Poyraz's avatar Suleyman Poyraz

Deleted tests

Testler başıma bela oldu
üst 0ad272e3
repos/*-bin/
repos/repo1/
repos/repo2/
repos/repo1-bin/
repos/repo2-bin/
repos/tmp/
inary-index.xml*
tests/
Inary UnitTests
##############
Before running unittests you need to first go to repos directory and
create test repositories.
>>> test@sulin tests/repos# python3 createrepos.py
Now you can return to tests folder and run tests.
>>> test@sulin tests # python3 runtests.py
# -*- coding: utf-8 -*-
#
# Copyright (C) 2018, Suleyman POYRAZ (Zaryob)
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your option)
# any later version.
#
# Please read the COPYING file.
#
# -*- coding: utf-8 -*-
#
# Copyright (C) 2018, Suleyman POYRAZ (Zaryob)
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your option)
# any later version.
#
# Please read the COPYING file.
#
import inary
import unittest
from . import testcase
class ComponentDBTestCase(testcase.TestCase):
def setUp(self):
testcase.TestCase.setUp(self)
self.componentdb = inary.db.componentdb.ComponentDB()
def testHasComponent(self):
assert self.componentdb.has_component("system.base", "repo1")
assert not self.componentdb.has_component("floct.flict", "repo1")
assert self.componentdb.has_component("applications.network", "repo2")
assert not self.componentdb.has_component("floct.flict", "repo2")
assert self.componentdb.has_component("applications.util")
def testListComponents(self):
assert set(self.componentdb.list_components("repo1")) == set(["system", "system.base",
"applications"])
assert set(self.componentdb.list_components("repo2")) == set(["applications", "applications.util",
"applications.network"])
assert set(self.componentdb.list_components()) == set(["system", "system.base",
"applications", "applications.network",
"applications.util"])
def testGetComponent(self):
component = self.componentdb.get_component("applications.network")
assert component.name == "applications.network"
assert "ncftp" in component.packages
assert "lynx" not in component.packages
component = self.componentdb.get_component("applications.network", "repo2")
assert component.name == "applications.network"
assert "lynx" in component.packages
assert "ncftp" not in component.packages
def testGetUnionComponent(self):
component = self.componentdb.get_union_component("applications.network")
assert component.name == "applications.network"
assert "lynx" in component.packages
assert "ncftp" in component.packages
def testGetPackages(self):
packages = self.componentdb.get_packages("applications.network")
assert "ncftp" in packages
assert "lynx" not in packages
packages = self.componentdb.get_packages("applications.network", "repo2")
assert "lynx" in packages
assert "ncftp" not in packages
packages = self.componentdb.get_packages("applications", "repo2", walk = True)
assert "cpulimit" and "lynx" in packages
assert "ncftp" not in packages
def testGetUnionPackages(self):
packages = self.componentdb.get_union_packages("applications.network")
assert "ncftp" in packages
assert "lynx" in packages
assert "cpulimit" not in packages
packages = self.componentdb.get_union_packages("applications", walk = True)
assert "ncftp" and "lynx" and "cpulimit" in packages
def testSearchComponent(self):
packages = self.componentdb.search_component(["applic"])
assert set(packages) == set(['applications', 'applications.network', 'applications.util'])
packages = self.componentdb.search_component(["system", "base"], repo="repo1")
assert set(packages) == set(["system.base"])
packages = self.componentdb.search_component(["system", "base"], repo="repo2")
assert not packages
# -*- coding: utf-8 -*-
#
# Copyright (C) 2018, Suleyman POYRAZ (Zaryob)
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your option)
# any later version.
#
# Please read the COPYING file.
#
import inary
import inary.context as ctx
import unittest
from . import testcase
class FilesDBTestCase(testcase.TestCase):
filesdb = inary.db.filesdb.FilesDB()
def testHasFile(self):
assert not self.filesdb.has_file("usr/bin/ethtool")
inary.api.install(["ethtool"])
assert self.filesdb.has_file("usr/bin/ethtool")
inary.api.remove(["ethtool"])
assert not self.filesdb.has_file("usr/bin/ethtool")
def testGetFile(self):
inary.api.install(["ethtool"])
pkg, path = self.filesdb.get_file("usr/bin/ethtool")
assert pkg == "ethtool"
assert path == "usr/bin/ethtool"
inary.api.remove(["ethtool"])
assert not self.filesdb.has_file("usr/bin/ethtool")
def testAddRemoveFiles(self):
fileinfo1 = inary.data.files.FileInfo()
fileinfo1.path = "etc/inary/inary.conf"
fileinfo2 = inary.data.files.FileInfo()
fileinfo2.path = "etc/inary/mirrors.conf"
files = inary.data.files.Files()
files.list.append(fileinfo1)
files.list.append(fileinfo2)
assert not self.filesdb.has_file("etc/inary/inary.conf")
assert not self.filesdb.has_file("etc/inary/mirrors.conf")
self.filesdb.add_files("inary", files)
assert self.filesdb.has_file("etc/inary/inary.conf")
assert self.filesdb.has_file("etc/inary/mirrors.conf")
pkg, path = self.filesdb.get_file("etc/inary/inary.conf")
assert pkg == "inary"
# FIXME: inconsistency in filesdb.py add_remove and remove_remove parameters
self.filesdb.remove_files(files.list)
assert not self.filesdb.has_file("etc/inary/inary.conf")
assert not self.filesdb.has_file("etc/inary/mirrors.conf")
def testSearchFile(self):
assert not self.filesdb.search_file("ethtool")
inary.api.install(["ethtool"])
found = self.filesdb.search_file("ethtool")
# -*- coding: utf-8 -*-
#
# Copyright (C) 2018, Suleyman POYRAZ (Zaryob)
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your option)
# any later version.
#
# Please read the COPYING file.
#
import inary
import unittest
from . import testcase
class InstallDBTestCase(testcase.TestCase):
def setUp(self):
testcase.TestCase.setUp(self)
self.installdb = inary.db.installdb.InstallDB()
def tearDown(self):
inary.api.remove(["ctorrent", "ethtool"])
def testGetPackage(self):
inary.api.install(["ethtool"])
idb = inary.db.installdb.InstallDB()
pkg = idb.get_package("ethtool")
assert type(pkg) == inary.metadata.Package
assert pkg.name == "ethtool"
def testHasPackage(self):
inary.api.install(["ethtool"])
self.installdb = inary.db.installdb.InstallDB()
assert not self.installdb.has_package("flipfloo")
assert self.installdb.has_package("ethtool")
def testListInstalled(self):
inary.api.install(["ethtool"])
self.installdb = inary.db.installdb.InstallDB()
assert set(self.installdb.list_installed()) == set(['zlib', 'pam', 'shadow',
'jpeg', 'libidn', 'db4',
'cracklib', 'openssl',
'curl', 'bash', 'ethtool'])
def testGetVersion(self):
inary.api.install(["ethtool"])
self.installdb = inary.db.installdb.InstallDB()
version, release, build = self.installdb.get_version("zlib")
assert version == "0.3"
assert release == "1"
assert build == None
def testGetFiles(self):
inary.api.install(["ethtool"])
self.installdb = inary.db.installdb.InstallDB()
files = self.installdb.get_files("ethtool")
assert files.list[0].path == "usr/bin/ethtool"
def testGetInfo(self):
inary.api.install(["ethtool"])
idb = inary.db.installdb.InstallDB()
info = idb.get_info("ethtool")
self.assertTrue(isinstance(info, inary.db.installdb.InstallInfo))
self.assertEqual(info.version, "0.3")
def testGetReverseDependencies(self):
inary.api.install(["ethtool"])
inary.api.install(["ctorrent"])
self.installdb = inary.db.installdb.InstallDB()
revdeps = self.installdb.get_rev_deps("openssl")
assert set(["ctorrent", "curl"]) == set(map(lambda x:x[0], revdeps))
def testAddRemovePackage(self):
inary.api.install(["ctorrent"])
self.installdb = inary.db.installdb.InstallDB()
assert self.installdb.has_package("ctorrent")
assert not self.installdb.has_package("ethtool")
inary.api.install(["ethtool"])
self.installdb = inary.db.installdb.InstallDB()
assert self.installdb.has_package("ctorrent")
assert self.installdb.has_package("ethtool")
def testMarkListPending(self):
inary.api.set_scom(False)
assert not self.installdb.has_package("ethtool")
inary.api.install(["ethtool"])
assert "ethtool" in self.installdb.list_pending()
inary.api.remove(["ethtool"])
assert "ethtool" not in self.installdb.list_pending()
inary.api.set_scom(True)
def testClearPending(self):
inary.api.set_scom(False)
assert not self.installdb.has_package("ethtool")
inary.api.install(["ethtool"])
assert "ethtool" in self.installdb.list_pending()
self.installdb.clear_pending("ethtool")
assert "ethtool" not in self.installdb.list_pending()
inary.api.remove(["ethtool"])
assert "ethtool" not in self.installdb.list_pending()
inary.api.set_scom(True)
def testSearchPackage(self):
self.installdb = inary.db.installdb.InstallDB()
assert not self.installdb.has_package("ethtool")
assert not self.installdb.search_package(["ethtool"])
inary.api.install(["ethtool"])
self.installdb = inary.db.installdb.InstallDB()
assert self.installdb.search_package(["et", "tool", "h"]) == ["ethtool"]
# -*- coding: utf-8 -*-
#
# Copyright (C) 2018, Suleyman POYRAZ (Zaryob)
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your option)
# any later version.
#
# Please read the COPYING file.
#
import unittest
from . import testcase
import inary.db.itembyrepo
class TestDB:
def __init__(self):
self.packages = {}
self.obsoletes = {}
self.packages["repo1"] = {"aggdraw":"package aggdraw",
"acpica":"package acpica"}
self.packages["repo2"] = {"kdiff3":"package kdiff3",
"kmess":"package kmess"}
self.obsoletes["repo1"] = ["wengophone", "rar"]
self.obsoletes["repo2"] = ["xara"]
self.tdb = inary.db.itembyrepo.ItemByRepo(self.packages)
self.odb = inary.db.itembyrepo.ItemByRepo(self.obsoletes)
# original item_repos in ItemByRepo uses repodb.list_repos
def item_repos(repo=None):
repos = ["repo1", "repo2"]
if repo:
repos = [repo]
return repos
self.tdb.item_repos = item_repos
self.odb.item_repos = item_repos
class ItemByRepoTestCase(testcase.TestCase):
testdb = TestDB()
def testHasRepository(self):
assert self.testdb.tdb.has_repo("repo1")
assert self.testdb.tdb.has_repo("repo2")
assert not self.testdb.tdb.has_repo("hedehodo")
def testHasItem(self):
assert self.testdb.tdb.has_item("kdiff3", "repo2")
assert not self.testdb.tdb.has_item("kdiff3", "repo1")
assert self.testdb.tdb.has_item("acpica")
def testWhichRepo(self):
assert self.testdb.tdb.which_repo("aggdraw") == "repo1"
assert self.testdb.tdb.which_repo("kmess") == "repo2"
def testGetItemAndRepository(self):
pkg, repo = self.testdb.tdb.get_item_repo("acpica")
assert pkg == "package acpica"
assert repo == "repo1"
pkg, repo = self.testdb.tdb.get_item_repo("kmess")
assert pkg == "package kmess"
assert repo == "repo2"
def testItemRepos(self):
db = inary.db.itembyrepo.ItemByRepo({})
assert db.item_repos("caracal") == ["caracal"]
# repos were created by testcase.py
assert db.item_repos() == ['repo1', 'repo2', 'repo1-src']
def testGetItem(self):
assert self.testdb.tdb.get_item("acpica") == "package acpica"
assert self.testdb.tdb.get_item("kmess") == "package kmess"
def testGetItemOfRepository(self):
assert self.testdb.tdb.get_item("acpica", "repo1") == "package acpica"
assert self.testdb.tdb.get_item("kmess", "repo2") == "package kmess"
def testGetItemKeys(self):
assert set(self.testdb.tdb.get_item_keys("repo1")) == set(["aggdraw", "acpica"])
assert set(self.testdb.tdb.get_item_keys("repo2")) == set(["kdiff3", "kmess"])
assert set(self.testdb.tdb.get_item_keys()) == set(["kdiff3", "kmess", "aggdraw", "acpica"])
def testGetListItem(self):
assert set(self.testdb.odb.get_list_item("repo1")) == set(['rar', 'wengophone'])
assert set(self.testdb.odb.get_list_item("repo2")) == set(['xara'])
assert set(self.testdb.odb.get_list_item()) == set(['rar', 'xara', 'wengophone'])
# -*- coding: utf-8 -*-
#
# Copyright (C) 2018, Suleyman POYRAZ (Zaryob)
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your option)
# any later version.
#
# Please read the COPYING file.
#
import unittest
from . import testcase
import inary.db.lazydb as lazydb
class TestDB(lazydb.LazyDB):
def init(self):
self.testfield = True
def getTestField(self):
return self.testfield
class LazyDBTestCase(testcase.TestCase):
def testDatabaseMethodForcingInit(self):
db = TestDB()
assert db.getTestField()
assert "testfield" in db.__dict__
db._delete()
def testDatabaseWithoutInit(self):
db = TestDB()
assert not "testfield" in db.__dict__
db._delete()
def testSingletonBehaviour(self):
db = TestDB()
db2 = TestDB()
assert id(db) == id(db2)
# -*- coding: utf-8 -*-
#
# Copyright (C) 2018, Suleyman POYRAZ (Zaryob)
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your option)
# any later version.
#
# Please read the COPYING file.
#
import unittest
from . import testcase
import inary
class PackageDBTestCase(testcase.TestCase):
def setUp(self):
testcase.TestCase.setUp(self)
self.packagedb = inary.db.packagedb.PackageDB()
def testGetPackage(self):
pkg = self.packagedb.get_package("ncftp", "repo1")
assert pkg.name == "ncftp"
pkg = self.packagedb.get_package("lynx", "repo2")
assert pkg.name == "lynx"
pkg = self.packagedb.get_package("cpulimit")
assert pkg.name == "cpulimit"
def testHasPackage(self):
assert self.packagedb.has_package("ncftp", "repo1")
assert not self.packagedb.has_package("ncftp", "repo2")
assert self.packagedb.has_package("lynx")
def testGetVersion(self):
version, release, build = self.packagedb.get_version("lynx", "repo2")
assert version == "0.3"
assert release == "1"
def testWhichRepo(self):
assert self.packagedb.which_repo("lynx") == "repo2"
def testGetPackageAndRepository(self):
pkg, repo = self.packagedb.get_package_repo("cpulimit")
assert pkg.name == "cpulimit"
assert repo == "repo2"
def testGetObsoletes(self):
assert set(self.packagedb.get_obsoletes("repo1")) == set(["wengophone", "rar"])
assert set(self.packagedb.get_obsoletes("repo2")) == set(["xara"])
assert set(self.packagedb.get_obsoletes()) == set(["wengophone", "rar", "xara"])
def testGetReverseDependencies(self):
pkg, dep = self.packagedb.get_rev_deps("openssl")[0]
assert pkg == "curl"
assert str(dep) == "openssl"
def testGetReplaces(self):
# FIXME: update createrepo.py to generate replaces
assert not self.packagedb.get_replaces()
def testListPackages(self):
assert set(self.packagedb.list_packages("repo1")) == set(['nfdump', 'ethtool', 'ncftp',
'libidn', 'zlib', 'db4', 'openssl',
'jpeg', 'pam', 'shadow', 'bogofilter',
'curl', 'gsl', 'bash', 'cracklib'])
assert set(self.packagedb.list_packages("repo2")) == set(['libpcap', 'ctorrent', 'lft', 'lynx',
'iat', 'cpulimit', 'rpl'])
def testSearchPackage(self):
packages = self.packagedb.search_package(["bogo", "filter"])
packages = ["bogofilter"]
packages = self.packagedb.search_package(["cpu", "limit"], repo="repo2")
packages = ["cpulimit"]
# -*- coding: utf-8 -*-
#
# Copyright (C) 2018, Suleyman POYRAZ (Zaryob)
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your option)
# any later version.
#
# Please read the COPYING file.
#
import inary
import unittest
from . import testcase
class RepoDBTestCase(testcase.TestCase):
def setUp(self):
testcase.TestCase.setUp(self)
self.repodb = inary.db.repodb.RepoDB()
def testAddRemoveRepo(self):
assert "repo2-src" not in self.repodb.list_repos()
repo = inary.db.repodb.Repo(inary.uri.URI("repos/repo2/inary-index.xml"))
self.repodb.add_repo("repo2-src", repo)
assert "repo2-src" in self.repodb.list_repos()
self.repodb.remove_repo("repo2-src")
assert "repo2" in self.repodb.list_repos()
assert "repo1" in self.repodb.list_repos()
assert "repo2-src" not in self.repodb.list_repos()
def testAddRemoveCycle(self):
for r in range(30):
assert "test-repo" not in self.repodb.list_repos()
repo = inary.db.repodb.Repo(inary.uri.URI("http://test-repo/inary-index.xml"))
self.repodb.add_repo("test-repo", repo)
assert "test-repo" in self.repodb.list_repos()
self.repodb.remove_repo("test-repo")
assert "test-repo" not in self.repodb.list_repos()
def testListRepos(self):
assert set(self.repodb.list_repos()) == set(['repo1', 'repo2', 'repo1-src'])
def testGetSourceRepos(self):
assert set(self.repodb.get_source_repos()) == set(['repo1-src'])
def testGetBinaryRepos(self):
assert set(self.repodb.get_binary_repos()) == set(['repo1', 'repo2'])
def testGetRepo(self):
repo = self.repodb.get_repo("repo1")
uri = repo.indexuri
assert uri.get_uri() == "repos/repo1-bin/inary-index.xml"
def testRepoOrder(self):
repoorder = inary.db.repodb.RepoOrder()
assert repoorder.get_order() == ['repo1', 'repo2', 'repo1-src']
repoorder.add("test-repo", "http://test-repo/inary-index.xml")
assert repoorder.get_order() == ['repo1', 'repo2', 'repo1-src', 'test-repo']
repoorder.remove("test-repo")
assert repoorder.get_order() == ['repo1', 'repo2', 'repo1-src']
# -*- coding: utf-8 -*-
#
# Copyright (C) 2018, Suleyman POYRAZ (Zaryob)
#
# This program is free software; you can redistribute it and/or modify it under the terms of the GNU General
# Public License as published by the Free Software Foundation; either version 3 of the License, or (at your
# option) any later version.
#
# Please read the COPYING file.
#
import unittest
from . import testcase
import os
import inary.operations.search
import inary.db as db
class SearchTestCase(testcase.TestCase):
def setUp(self):
testcase.TestCase.setUp(self, database = True)
def testSearch(self):
doc1 = "A set object is an unordered collection of immutable values."
doc2 = "Being an unordered collection, sets do not record element position or order of insertion."
doc3 = "There are currently two builtin set types, set and frozenset"
inary.search.init(['test'], ['en'])
inary.search.add_doc('test', 'en', 1, doc1, repo = db.itembyrepo.installed)
inary.search.add_doc('test', 'en', 2, doc2, repo = db.itembyrepo.installed)
inary.search.add_doc('test', 'en', 3, doc3, repo = db.itembyrepo.installed)
q1 = inary.search.query('test', 'en', ['set'], repo = db.itembyrepo.alldb)
self.assertEqual(q1, set([1,3]))
q2 = inary.search.query('test', 'en', ['an', 'collection'], repo = db.itembyrepo.alldb)
self.assertEqual(q2, set([1,2]))
inary.search.finalize()
# -*- coding: utf-8 -*-
#
# Copyright (C) 2018, Suleyman POYRAZ (Zaryob)
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your option)
# any later version.
#
# Please read the COPYING file.
#
import unittest
from . import testcase
import inary
class SourceDBTestCase(testcase.TestCase):
def setUp(self):
testcase.TestCase.setUp(self)
self.sourcedb = inary.db.sourcedb.SourceDB()
def testListSources(self):
assert set(self.sourcedb.list_sources()) == set(['ethtool', 'nfdump', 'shadow', 'libidn',
'zlib', 'db4', 'openssl', 'jpeg', 'gsl',
'curl', 'bogofilter', 'ncftp', 'pam',
'bash', 'cracklib'])
def testHasSpec(self):
assert self.sourcedb.has_spec("ethtool")
assert not self.sourcedb.has_spec("hedehodo")
def testGetSpec(self):
spec = self.sourcedb.get_spec("ethtool")
assert spec.source.name == "ethtool"
assert spec.source.partOf == "applications.network"
def testGetSpecOfRepository(self):
spec = self.sourcedb.get_spec("ethtool", "repo1-src")
assert spec.source.name == "ethtool"
assert spec.source.partOf == "applications.network"
def testGetSpecAndRepository(self):
spec, repo = self.sourcedb.get_spec_repo("ethtool")
assert spec.source.name == "ethtool"
assert spec.source.partOf == "applications.network"
assert repo == "repo1-src"
def testGetSourceFromPackage(self):
# FIXME: Add multi package from source to createrepo.py
pkg = self.sourcedb.pkgtosrc("cracklib")
assert pkg == "cracklib"
def testSearchPackage(self):
packages = self.sourcedb.search_spec(["open", "ssl"])
assert set(["openssl"]) == set(packages)
packages = self.sourcedb.search_spec(["bogo", "filter"], repo="repo1-src")
assert set(["bogofilter"]) == set(packages)
import unittest
import inary
import inary.context as ctx
class TestCase(unittest.TestCase):
def setUp(self):
options = inary.config.Options()
options.destdir = 'repos/tmp'
inary.api.set_options(options)
inary.api.set_scom(False)
ctx.config.values.general.distribution = "Sulin"
ctx.config.values.general.distribution_release = "2018"
if not inary.api.list_repos():
inary.api.add_repo("repo1", "repos/repo1-bin/inary-index.xml")
inary.api.add_repo("repo2", "repos/repo2-bin/inary-index.xml")
inary.api.add_repo("repo1-src", "repos/repo1/inary-index.xml")
inary.api.update_repo("repo1")
inary.api.update_repo("repo2")
inary.api.update_repo("repo1-src")
import inary
import unittest
from inary import util
from inary import uri
from inary import archive
from inary import sourcearchive
from inary import fetcher
from inary.data.specfile import SpecFile
from os.path import join, exists
class ArchiveTestCase(unittest.TestCase):
def testTarUnpack(self):
spec = SpecFile('repos/repo1/system/base/bash/pspec.xml')
targetDir = '/tmp/tests'
archives = sourcearchive.SourceArchives(spec)
archives.unpack(targetDir)
for archive in spec.source.archive:
assert archive.type == 'targz'
def testUnpackTarCond(self):
spec = SpecFile('repos/repo1/system/base/zlib/pspec.xml')
targetDir = '/tmp'
archives = sourcearchive.SourceArchives(spec)
for archive in spec.source.archive:
url = uri.URI(archive.uri)
filePath = join(inary.context.config.archives_dir(), url.filename())
if util.sha1_file(filePath) != archive.sha1sum:
fetch = fetcher.Fetcher(archive.uri, targetDir)
fetch.fetch()
assert archive.type == 'tarbz2'
def testZipUnpack(self):
spec = SpecFile('repos/repo1/applications/network/bogofilter/pspec.xml')
targetDir = '/tmp/tests'
archives = sourcearchive.SourceArchives(spec)
archives.fetch()
archives.unpack(targetDir)
assert not exists(targetDir + '/openssl')
def testMakeZip(self):
spec = SpecFile('repos/repo1/applications/network/gsl/pspec.xml')
targetDir = '/tmp/tests'
archives = sourcearchive.SourceArchives(spec)
archives.fetch(interactive = False)
archives.unpack(targetDir, clean_dir=True)
del archives
newDir = targetDir + '/newZip'
zip = archive.ArchiveZip(newDir, 'zip', 'w')
sourceDir = '/tmp/inary-root'
zip.add_to_archive(sourceDir)
zip.close()
import unittest
from inary.data.specfile import SpecFile
from inary import uri
from inary.file import File
class FileTestCase(unittest.TestCase):
def setUp(self):
unittest.TestCase.setUp(self)
def testMakeUri(self):
spec = SpecFile("repos/repo1/system/base/bash/pspec.xml")
url = uri.URI(spec.source.archive[0].uri)
self.assertTrue(File.make_uri(url))
def testChooseMethod(self):
compress = File('repos/repo2/inary-index.xml', File.read)
self.assertTrue(File.choose_method('inary.conf', compress))
def testDecompress(self):
localfile = File('repos/repo1/system/base/bash/pspec.xml', File.read)
compress = File('repos/repo2/inary-index.xml', File.read)
self.assertTrue(File.decompress(localfile,compress))
def testLocalFile(self):
f = File('repos/repo1/system/base/curl/pspec.xml', File.read)
r = f.readlines()
assert (len(r) > 0)
def testRemoteRead(self):
f = File('http://www.sulin.org.tr/Releases/2018/roadmap.html', File.read)
r = f.readlines()
assert (len(r) > 0)
import unittest
import inary.sourcearchive
from inary.data.specfile import SpecFile
class SourceArchiveTestCase(unittest.TestCase):
def testFetch(self):
spec = SpecFile('repos/repo1/system/base/bash/pspec.xml')
srcarch = inary.sourcearchive.SourceArchive(spec.source.archive[0])
self.assertTrue(not srcarch.fetch())
def testIscached(self):
spec = SpecFile('repos/repo1/system/base/bash/pspec.xml')
srcarch = inary.sourcearchive.SourceArchive(spec.source.archive[0])
assert srcarch.is_cached()
def testIscached(self):
spec = SpecFile('repos/repo1/system/base/bash/pspec.xml')
targetDir = '/tmp/tests'
srcarch = inary.sourcearchive.SourceArchive(spec.source.archive[0])
self.assertTrue(not srcarch.unpack(targetDir))
def testUnpack(self):
spec = SpecFile('repos/repo1/system/base/bash/pspec.xml')
targetDir = '/tmp/tests'
srcarch = inary.sourcearchive.SourceArchive(spec.source.archive[0])
srcarch.unpack(targetDir)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2018, Suleyman POYRAZ (Zaryob)
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 3 of the License, or (at your option)
# any later version.
#
# Please read the COPYING file.
from inary.actionsapi import cmaketools
from inary.actionsapi import inarytools
from inary.actionsapi import shelltools
from inary.actionsapi import get
WorkDir = "helloworld"
def setup():
cmaketools.configure()
def build():
cmaketools.make()
def install():
cmaketools.install()
inarytools.dodir("/var/opt/helloworld")
inarytools.dobin("helloworld", "/var/opt/helloworld")
tar cvf helloworld.tar helloworld
tar cjvf helloworld.tar.bz2 helloworld
tar cjvf helloworld.tar.gz helloworld
tar cjvf helloworld.tar.xz helloworld
PROJECT (helloworld)
# CMake 2.6 required
CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
# Python is required
FIND_PACKAGE(PkgConfig)
# Application name
SET (APP_NAME "helloworld")
SET (APP_SUFFIX "2")
# Uncomment this for production releases.
SET (VERSION_SUFFIX "")
#SET (FLAGS "-g -O0 -Wcast-align -Wno-uninitialized -Wall -fstrict-aliasing")
SET (FLAGS "-g -O0 -Wno-uninitialized -Wall -fstrict-aliasing")
# Uncomment this for gprof profiling
# SET (FLAGS "-g -O0 -Werror -Wcast-align -Wno-uninitialized -Wall -fstrict-aliasing -fprofile-arcs -ftest-coverage")
SET (CMAKE_C_FLAGS "${FLAGS}")
# Uncomment this for sparse building
# SET (CMAKE_C_COMPILER cgcc)
# Append name suffix, if specified
IF (APP_SUFFIX)
SET (APP_NAME "${APP_NAME}${APP_SUFFIX}")
ENDIF (APP_SUFFIX)
INCLUDE_DIRECTORIES (include/)
# Define version, config dir, data dir and log file.
SET (SOURCES src/helloworld.cxx
src/utility.cxx)
# Compile scom from specified sources
ADD_EXECUTABLE (helloworld ${SOURCES})
# Install scom to /usr/bin/<app-name>
INSTALL (PROGRAMS helloworld
DESTINATION /usr/bin)
//
//
// ANSI Standard C++ Library Includes
//
//
// C++ Standard Library
#include <typeinfo>
#include <stdexcept>
#include <memory>
#include <new>
// Containers
#include <string>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <valarray>
#include <iterator>
#include <algorithm>
#include <functional>
#include <numeric>
// Adaptors
#include <queue>
#include <stack>
// I/O
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <locale>
#include <cstdlib>
#include <cstdio>
#include <cassert>
#include <cerrno>
#include <cfloat>
#include <cmath>
#include <csetjmp>
#include <csignal>
#include <ctime>
#include <cstring>
#include <clocale>
using namespace std;
// General Interface file
#ifndef General_Interface
#define General_Interface
#include "ciso.hxx"
#include "utility.hxx"
#endif
#ifndef Utility_Interface
#define Utility_Interface
#include "general.hxx"
namespace Utility {
class CPU_Time {
public:
CPU_Time() : clock_rep( clock() ) {} // current time
CPU_Time(clock_t c) : clock_rep(c) {}
//Time(time_t t) : time_rep(t) {}
//operator const time_t() { return time_rep; }
CPU_Time operator -(const CPU_Time rhs) {
return CPU_Time(clock_rep - rhs.clock_rep);
}
ostream& print(ostream& out = cout) {
out << double(clock_rep)/CLOCKS_PER_SEC << " seconds";
return out;
}
private:
clock_t clock_rep;
};
inline ostream& operator <<(ostream& out, CPU_Time t) {
return t.print(out);
}
// simple counter class
class Counter {
public:
Counter(int val): value(val) {}
int operator()() { return value++; }
int check() { return value; }
private:
int value;
};
// wrapper for rand functions
class Rand {
public:
static void init() {
seed += time(0);
srand(seed);
srand(rand());
}
static double rand_double (double upper_bound) {
return double(rand()) * upper_bound / RAND_MAX;
}
static int rand_int (int upper_bound) {
return rand() % upper_bound;
}
private:
static int seed;
};
} // namespace
#endif
#include "general.hxx"
int main(int argc, char *argv[])
{
cout << "Hello world" << endl;
return 0;
}
#include "utility.hxx"
namespace Utility {
int Rand::seed;
}
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<!DOCTYPE INARY SYSTEM "http://sulin.org/test/inary/inary-spec.dtd">
<INARY>
<Source>
<Name>helloworld</Name>
<Homepage>http://www.uludag.org.tr</Homepage>
<Packager>
<Name>John Blonde</Name>
<Email>john@blonde.com</Email>
</Packager>
<License>GPL-2</License>
<IsA>category</IsA>
<PartOf>component</PartOf>
<Summary xml:lang="en">ActionsAPI test suit</Summary>
<Description xml:lang="en">ActionsAPI test suit</Description>
<Archive type="tarxz" sha1sum="650ff7153aaec65aef71563068154617ca8913d0">http://localhost/helloworld.tar.xz</Archive>
</Source>
<Package>
<Name>helloworld</Name>
<Files>
<Path fileType="binary">/</Path>
</Files>
</Package>
<History>
<Update release="1">
<Date>2018-04-28</Date>
<Version>2.0</Version>
</Update>
</History>
</INARY>
<INARY>
<Operation type="upgrade" date="2008-01-14" time="15:10">
<Package operation="upgrade">
<Name>gdb</Name>
<Before version="6.6" release="8" build="9"/>
<After version="6.6" release="9" build="10"/>
</Package>
<Package operation="upgrade">
<Name>rsync</Name>
<Before version="2.6.9" release="8" build="4"/>
<After version="2.6.9" release="12" build="7"/>
</Package>
<!-- In an upgrade operation this package is removed. Probably a conflicted package. -->
<Package operation="remove">
<Name>hashalot</Name>
<Before version="2.3.6" release="20" build="23"/>
</Package>
<!-- In an upgrade operation this package is installed. Must be a new dependency. -->
<Package operation="install">
<Name>XML-DOM</Name>
<After version="1.44" release="1" build="1"/>
</Package>
</Operation>
</INARY>
<INARY>
<Operation type="remove" date="2008-01-16" time="15:00">
<Package operation="remove">
<Name>gdb</Name>
<Before version="6.6" release="8" build="9"/>
</Package>
<Package operation="remove">
<Name>rsync</Name>
<Before version="2.6.9" release="8" build="4"/>
</Package>
</Operation>
</INARY>
<INARY>
<Operation type="install" date="2008-01-11" time="15:20">
<Package operation="install">
<Name>gdb</Name>
<After version="6.6" release="9" build="10"/>
</Package>
<!-- This is a reinstalled package. -->
<Package operation="reinstall">
<Name>rsync</Name>
<Before version="2.6.9" release="8" build="4"/>
<After version="2.6.9" release="8" build="4"/>
</Package>
<Package operation="downgrade">
<Name>apackage</Name>
<Before version="1.3" release="12" build="9"/>
<After version="1.3" release="6" build="2"/>
</Package>
<Package operation="install">
<Name>xyz</Name>
<After version="2.6.9" release="12" build="7"/>
</Package>
<!-- In an install operation this package is removed. Probably a conflicted package. -->
<Package operation="remove">
<Name>hashalot</Name>
<Before version="2.3.6" release="20" build="23"/>
</Package>
</Operation>
</INARY>
<INARY>
<Operation type="snapshot" date="2008-01-14" time="15:28">
<Package operation="snapshot">
<Name>readline</Name>
<Before version="2.3.6" release="20" build="23"/>
</Package>
<Package operation="snapshot">
<Name>gdb</Name>
<Before version="6.6" release="8" build="9"/>
</Package>
<Package operation="snapshot">
<Name>rsync</Name>
<Before version="2.6.9" release="8" build="4"/>
</Package>
</Operation>
</INARY>
import unittest
from inary.configfile import ConfigurationFile
class ConfigFileTestCase(unittest.TestCase):
def setUp(self):
self.cf = ConfigurationFile('inary.conf')
def testGeneralDefaults(self):
cf = self.cf
self.assertEqual(cf.general.destinationDirectory, cf.general['destinationDirectory'])
assert not cf.general.autoclean
self.assertEqual(cf.general.http_proxy, cf.general['http_proxy'])
assert not cf.general.package_cache
def testBuildDefaults(self):
cf = self.cf
self.assertEqual(cf.build.jobs, cf.build['jobs'])
assert not cf.build.defaults.generateDebug
assert cf.build.defaults.enableSandbox
self.assertEqual(cf.build.compressionlevel, cf.build['compressionlevel'])
self.assertEqual(cf.build.fallback, cf.build['fallback'])
def testDirectoriesDefaults(self):
cf = self.cf
self.assertEqual(cf.dirs.lib_dir, cf.dirs['lib_dir'])
self.assertEqual(cf.dirs.index_dir, cf.dirs['index_dir'])
def testConfigurationSection(self):
cf = self.cf
if not cf.general:
self.fail()
if not cf.build:
self.fail()
if not cf.dirs:
self.fail()
def testInaryConfValues(self):
cf = self.cf
self.assertEqual(cf.dirs.kde_dir, '/usr/kde/5')
self.assertEqual(cf.dirs.compiled_packages_dir, '/var/cache/inary/packages')
self.assertEqual(cf.general.architecture, 'i686')
self.assertEqual(cf.general.distribution_release, '2018')
def testValuesExists(self):
cf = self.cf
assert cf.general.distribution
assert not cf.general.targetDirectory
assert cf.build.cxxflags
assert not cf.build.configurationlevel
assert cf.dirs.qt_dir
assert not cf.dirs.cache_dir
import unittest
import inary.constants
import inary.context as ctx
class ConstantTestCase(unittest.TestCase):
def testConstants(self):
constants = ctx.const
constDict = {"actions": "actions.py", "setup":"setup","metadata":"metadata.xml"}
for i in list(constDict.keys()):
if hasattr(constants,i):
value = getattr(constants,i)
self.assertEqual(value, constDict[i])
import unittest
import os
import base64
import inary.context as ctx
import inary.api
from inary.data.specfile import SpecFile
from inary.fetcher import Fetcher
from inary import util
from inary import uri
class FetchTestCase(unittest.TestCase):
def setUp(self):
unittest.TestCase.setUp(self)
self.spec = SpecFile()
self.spec.read('repos/repo1/system/base/openssl/pspec.xml')
self.url = uri.URI(self.spec.source.archive[0].uri)
self.url.set_auth_info(("user", "pass"))
self.destpath = ctx.config.archives_dir()
self.fetch = Fetcher(self.url, self.destpath)
def testFetch(self):
self.fetch.fetch()
fetchedFile = os.path.join(self.destpath, self.url.filename())
if os.access(fetchedFile, os.R_OK):
self.assertEqual(util.sha1_file(fetchedFile),self.spec.source.archive[0].sha1sum)
os.remove(fetchedFile)
def testFetcherFunctions(self):
enc = base64.encodestring('{0}:{0}'.format(self.url.auth_info()))
self.assertEqual(self.fetch._get_http_headers(),(('Authorization', 'Basic {}'.format(enc)),))
assert not self.fetch._get_ftp_headers()
# Copyright (C) 2018, Suleyman POYRAZ (Zaryob)
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your option)
# any later version.
#
# Please read the COPYING file.
#
import unittest
from inary.mirrors import Mirrors
class MirrorsTestCase(unittest.TestCase):
def testGetMirrors(self):
mirrors = Mirrors("mirrors.conf")
assert ["http://www.eu.apache.org/dist/"] == mirrors.get_mirrors("apache")
assert ['http://search.cpan.org/CPAN/', 'http://cpan.ulak.net.tr/'] == mirrors.get_mirrors("cpan")
assert ["http://ftp.gnu.org/gnu/"] == mirrors.get_mirrors("gnu")
import unittest
import inary
import inary.actionsapi
import os
import shutil
class ShellTestCase(unittest.TestCase):
def setUp(self):
from inary.actionsapi.variables import initVariables
unittest.TestCase.setUp(self)
initVariables()
return
def testCanAccessFile(self):
from inary.actionsapi.shelltools import can_access_file
assert can_access_file(__file__)
assert not can_access_file('actionsapi/set.py')
def testCanAccessDirectory(self):
from inary.actionsapi.shelltools import can_access_directory
assert can_access_directory('/boot')
assert can_access_directory('/usr/bin')
assert not can_access_directory('/tests/mirrors.conf')
def testMakedirs(self):
from inary.actionsapi.shelltools import makedirs
makedirs('tests/testdirectory/aDirectory')
self.assertEqual(os.path.exists('tests/testdirectory/aDirectory'),True)
shutil.rmtree('tests/testdirectory')
def testEcho(self):
from inary.actionsapi.shelltools import echo
echo('tests/echo-file','eco subject')
self.assertEqual(os.path.exists('tests/echo-file'),True)
self.assertEqual(open('tests/echo-file').readlines()[0].strip(), 'eco subject')
echo('tests/echo-file', 'subject eco')
self.assertEqual(open('tests/echo-file').readlines()[1].strip(), 'subject eco')
os.remove('tests/echo-file')
def testSym(self):
from inary.actionsapi.shelltools import sym
sym('../../scenarios/repo','tests/repos')
self.assertEqual(os.path.islink('tools'),False)
self.assertEqual(os.path.islink('tests/repos'),True)
def testUnlinkDir(self):
from inary.actionsapi.shelltools import makedirs
from inary.actionsapi.shelltools import sym
from inary.actionsapi.shelltools import unlinkDir
makedirs('tests/testdirectory/sample')
sym('testdirectory/sample', 'tests/history')
self.assertEqual(os.path.islink('tests/history'), True)
unlinkDir('tests/testdirectory/sample')
self.assertEqual(os.path.islink('tests/testdirectory/sample'), False)
def testCopy(self):
from inary.actionsapi.shelltools import echo
from inary.actionsapi.shelltools import copy
from inary.actionsapi.shelltools import makedirs
makedirs('tests/testdirectory/sample')
copy('tests', 'tests-copy')
self.assertEqual(os.path.islink('tests-copy'), False)
shutil.rmtree("tests-copy")
echo('tests/echo-file', 'subject eco')
copy('tests/echo-file', 'tests/echo-file-copy')
self.assertEqual(os.path.islink('tests/echo-file-copy'), False)
os.remove("tests/echo-file")
def testIsLink(self):
from inary.actionsapi.shelltools import sym
from inary.actionsapi.shelltools import isLink
sym('../database', 'tests/history')
assert isLink('tests/history')
assert not isLink('tests/runtests.py')
def testIsFile(self):
from inary.actionsapi.shelltools import isFile
assert isFile('/bin/bash')
assert not isFile('/tests/database')
def testIsDirectory(self):
from inary.actionsapi.shelltools import isDirectory
assert not isDirectory('doc/dependency.pdf')
assert isDirectory('/usr/lib')
assert isDirectory('/etc/inary')
assert not isDirectory('tests/shelltest.py')
def testRealPath(self):
from inary.actionsapi.shelltools import realPath
assert realPath('doc/dependency.pdf')
assert realPath('tests/database/sourcedbtest.py')
def testBaseName(self):
from inary.actionsapi.shelltools import baseName
assert 'dependency.pdf' == baseName('doc/dependency.pdf')
assert 'Arphic' == baseName('licenses/Arphic')
assert not 'Atmel' == baseName('tools/atmel.py')
def testSystem(self):
from inary.actionsapi.shelltools import system
self.assertEqual(os.path.exists('tests/systemtest'),False)
system('touch tests/systemtest')
self.assertEqual(os.path.exists('tests/systemtest'),True)
os.remove('tests/systemtest')
import unittest
import os
from inary import uri
from inary.file import File
from inary.data.specfile import SpecFile
class UriTestCase(unittest.TestCase):
def setUp(self):
unittest.TestCase.setUp(self)
def testSetUri(self):
self.url = uri.URI()
self.url.set_uri('uri')
assert 'uri' == self.url.get_uri()
self.url.set_uri('urix')
assert 'urix' == self.url.get_uri()
def testIsLocalFile(self):
uri1 = uri.URI()
assert not uri1.is_local_file()
uri1.set_uri('/usr/local')
assert uri1.is_local_file()
def testIsRemoteFile(self):
uri2 = uri.URI()
assert uri2.is_remote_file()
uri2.set_uri('uri')
assert not uri2.is_remote_file()
def testSchemePath(self):
uri3 = uri.URI()
uri3.set_uri('/usr/bin')
self.assertEqual('file', uri3.scheme())
assert '/usr/bin' == uri3.path()
def testFileName(self):
uri4 = uri.URI()
uri4.set_uri('/usr/share/aclocal')
assert 'aclocal' == uri4.filename()
import unittest
import shutil
from inary.util import *
import os
class UtilTestCase(unittest.TestCase):
def initialize(self):
testcase.testCase.initialize(self, database=False)
#process related functions
def testRunBatch(self):
assert (0, b'', b'') == run_batch('cd')
assert (127, b'', b'/bin/sh: 1: add: not found\n') == run_batch('add')
def testRunLogged(self):
assert 0 == run_logged('ls')
assert 1 == run_logged('rm')
def testXtermTitle(self):
xterm_title('sulin')
xterm_title_reset()
#path processing functions tests
def testSplitPath(self):
assert ['usr', 'local', 'src'] == splitpath('usr/local/src')
assert ['usr', 'lib', 'sulin'] == splitpath('usr/lib/sulin')
def testSubPath(self):
self.assertTrue(subpath('usr','usr'))
self.assertTrue(subpath('usr','usr/local/src'))
self.assertTrue(not subpath('usr/local','usr'))
def testRemovePathPrefix(self):
pathname = removepathprefix('usr/local', 'usr/local/src')
assert 'src' == pathname
pathname = removepathprefix('usr/local','usr/local/bin')
assert not 'bim' == pathname
def testJoinPath(self):
assert 'usr/local/src' == join_path('usr/local','src')
assert not 'usr/lib/hal' == join_path('usr','hal')
assert 'usr/sbin/lpc' == join_path('usr','sbin/lpc')
#file/directory related functions tests
def testCheckFile(self):
assert check_file('/etc/inary/inary.conf')
assert check_file('/usr/bin/aatest')
def testCleanDir(self):
assert None == clean_dir('usr/lib')
assert None == clean_dir('usr/local')
assert not 'tmp/inary-root' == clean_dir('usr/tmp')
def testDirSize(self):
self.assertNotEqual(dir_size('usr/lib/sulin'),2940)
self.assertNotEqual(dir_size('usr/lib'),65)
def testCopyFile(self):
copy_file('/etc/inary/inary.conf', '/tmp/inary-test1')
copy_file('/etc/inary/sandbox.conf', '/tmp/inary-test2')
copy_file_stat('/etc/inary/inary.conf', '/tmp/inary-test1')
# Copyright (C) 2018, Suleyman POYRAZ (Zaryob)
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your option)
# any later version.
#
# Please read the COPYING file.
#
import unittest
from inary.version import Version
class VersionTestCase(unittest.TestCase):
def setUp(self):
pass
def testSingle(self):
v1 = Version("103")
v2 = Version("90")
self.assertTrue(v1 > v2)
def testOpsNumerical(self):
v1 = Version("0.3.1")
v2 = Version("0.3.5")
v3 = Version("1.5.2")
v4 = Version("0.3.1")
v5 = Version("2.07")
self.assertTrue(v1 < v2)
self.assertTrue(v3 > v2)
self.assertTrue(v1 <= v3)
self.assertTrue(v4 >= v4)
self.assertTrue(v5 > v3)
def testOpsKeywords(self):
# with keywords
v1 = Version("2.23_pre10")
v2 = Version("2.23")
v3 = Version("2.21")
v4 = Version("2.23_p1")
v5 = Version("2.23_beta1")
v6 = Version("2.23_m1")
v7 = Version("2.23_rc1")
v8 = Version("2.23_rc2")
self.assertTrue(v1 < v2)
self.assertTrue(v1 > v3)
self.assertTrue(v1 < v4)
self.assertTrue(v1 > v5)
self.assertTrue(v2 < v4)
self.assertTrue(v2 > v5)
self.assertTrue(v6 < v4)
self.assertTrue(v6 > v5)
self.assertTrue(v7 > v5)
self.assertTrue(v8 > v7)
v1 = Version("1.0_alpha1")
v2 = Version("1.0_alpha2")
self.assertTrue(v2 > v1)
def testOpsCharacters(self):
# with character
v1 = Version("2.10a")
v2 = Version("2.10")
v3 = Version("2.10d")
self.assertTrue(v1 > v2)
self.assertTrue(v1 < v3)
self.assertTrue(v2 < v3)
def testGeBug(self):
# bug 603
v1 = Version('1.8.0')
v2 = Version('1.9.1')
self.assertTrue( not v1 > v2 )
self.assertTrue( not v1 >= v2 )
<?xml version="1.0" ?>
<INARY>
<Source>
<Name>
popt
</Name>
<Packager>
<Name>
Kırmızı kafalar
</Name>
<Email>
hotmail@redhat.com
</Email>
</Packager>
</Source>
<Package>
<Name>
popt-libs
</Name>
<Summary>
Command line option parsing library
</Summary>
<Description>
library files for popt
</Description>
<License>
As-Is
</License>
<IsA>
library:util:optparser
</IsA>
<PartOf>
rpm:archive
</PartOf>
<RuntimeDependencies>
<Dependency>
gettext
</Dependency>
</RuntimeDependencies>
<Files>
<Path fileType="sharedLib">
/usr/lib
</Path>
<Path fileType="doc">
/usr/share/doc
</Path>
<Path fileType="doc">
/usr/share/man
</Path>
<Path fileType="localedata">
/usr/share/locale
</Path>
<Path fileType="header">
/usr/include/popt.h
</Path>
</Files>
<History>
<Update release="3">
<Date>2005-06-14</Date>
<Version>1.7</Version>
</Update>
<Update release="2">
<Date>2005-06-10</Date>
<Version>1.7</Version>
</Update>
<Update release="3">
<Date>2005-05-05</Date>
<Version>1.7</Version>
</Update>
</History>
<Build>
0
</Build>
<Distribution>
Pardus
</Distribution>
<DistributionRelease>
0.1
</DistributionRelease>
<Architecture>
Any
</Architecture>
<InstalledSize>
149691
</InstalledSize>
</Package>
</INARY>
apache http://www.eu.apache.org/dist/
cpan http://search.cpan.org/CPAN/
cpan http://cpan.ulak.net.tr/
gnu http://ftp.gnu.org/gnu/
<INARY>
<Source>
<Name>
popt
</Name>
<Packager>
<Name>
Kırmızı kafalar
</Name>
<Email>
hotmail@redhat.com
</Email>
</Packager>
</Source>
<Package>
<Name>
popt-libs
</Name>
<Summary>
Command line option parsing library
</Summary>
<Description>
library files for popt
</Description>
<License>
As-Is
</License>
<IsA>
library:util:optparser
</IsA>
<PartOf>
rpm:archive
</PartOf>
<RuntimeDependencies>
<Dependency>
gettext
</Dependency>
</RuntimeDependencies>
<Files>
<Path fileType="sharedLib">
/usr/lib
</Path>
<Path fileType="doc">
/usr/share/doc
</Path>
<Path fileType="doc">
/usr/share/man
</Path>
<Path fileType="localedata">
/usr/share/locale
</Path>
<Path fileType="header">
/usr/include/popt.h
</Path>
</Files>
<History>
<Update release="3">
<Date>2005-06-14</Date>
<Version>1.7</Version>
</Update>
<Update release="2">
<Date>2005-06-10</Date>
<Version>1.7</Version>
</Update>
<Update release="3">
<Date>2005-05-05</Date>
<Version>1.7</Version>
</Update>
</History>
<Build>
0
</Build>
<Distribution>
Pardus
</Distribution>
<DistributionRelease>
0.1
</DistributionRelease>
<Architecture>
Any
</Architecture>
<InstalledSize>
149691
</InstalledSize>
</Package>
</INARY>
# -*- coding: utf-8 -*-
import unittest
import inary
import inary.context as ctx
import inary.analyzer.conflict
class ConflictTestCase(unittest.TestCase):
def testInstalledPackageConflicts(self):
inary.api.install(["ethtool"])
confinfo = inary.analyzer.conflict.Conflict()
confinfo.package = "ethtool"
confinfo.version = "6"
confinfo.release = "1"
assert not inary.analyzer.conflict.installed_package_conflicts(confinfo)
inary.api.remove(["ethtool"])
def testCalculateConflicts(self):
packagedb = inary.db.packagedb.PackageDB()
packages = ["ethtool", "zlib", "ctorrent"]
assert inary.analyzer.conflict.calculate_conflicts(packages, packagedb)
def testConflictCheck(self):
# In our sample repo1, inary.analyzer.conflicts with bar.
# If this fails, it may affect database test case results.
inary.api.update_repo("repo1")
inary.api.install(["inary"])
myconflict = inary.analyzer.conflict.Conflict()
myconflict.package = "bar"
myconflict.version = "0.3"
myconflict.release = "1"
inary.api.install(["bar"])
assert "bar" in inary.api.list_installed()
assert "inary" not in inary.api.list_installed()
inary.api.remove(["bar"])
def testInterRepoCrossConflicts(self):
#If this fails, it may affect database test case results
inary.api.update_repo("repo1")
inary.api.install(["inary", "foo"])
before = inary.api.list_installed()
inary.api.update_repo("repo2")
inary.api.upgrade(["inary"])
after = inary.api.list_installed()
assert set(before) == set(after)
idb = inary.db.installdb.InstallDB()
assert 3 == int(idb.get_package("foo").release)
inary.api.remove(["foo"])
inary.api.remove(["inary"])
import unittest
import inary.data.relation
import inary.analyzer.dependency
class DependencyTestCase(unittest.TestCase):
def testDictSatisfiesDep(self):
inary.api.install(["uif2iso"])
relation = inary.data.relation.Relation()
relation.package = "uif2iso"
inary.api.install(["minizip"])
rel = inary.data.relation.Relation()
rel.package = "minizip"
depinfo = inary.analyzer.dependency.Dependency(relation)
dictionary = {"ethtool": [" "],"minizip":["zlib"]}
assert not depinfo.satisfied_by_dict_repo(dictionary)
depinf = inary.analyzer.dependency.Dependency(rel)
assert not depinf.satisfied_by_dict_repo(dictionary)
def testInstalledSatisfiesDep(self):
inary.api.install(["uif2iso"])
relation = inary.data.relation.Relation()
relation.package = "uif2iso"
depinfo = inary.analyzer.dependency.Dependency(relation)
assert not depinfo.satisfied_by_installed()
def testRepoSatisfiesDependency(self):
inary.api.install(["uif2iso"])
relation = inary.data.relation.Relation()
relation.package = "uif2iso"
depinfo = inary.analyzer.dependency.Dependency(relation)
assert not depinfo.satisfied_by_repo()
import unittest
import inary.data.files
class FilesTestCase(unittest.TestCase):
def setUp(self):
unittest.TestCase.setUp(self)
def testFileInfo(self):
file1 = inary.data.files.FileInfo(path = '/usr/bin/acpi')
file1.type = 'init'
file1.size = '30'
file2 = inary.data.files.FileInfo(path = '/sbin/blkid', type = 'ctors', size = '8')
def testFiles(self):
self.files = inary.data.files.Files()
self.files.read('repos/repo1/system/base/bash/pspec.xml')
import unittest
import inary.data.relation
class HistoryTestCase(unittest.TestCase):
def testCreate(self):
history = inary.data.history.History()
operation = 'upgrade'
history.create(operation)
history.create('install')
history.create('snapshot')
def testGetLatest(self):
history = inary.data.history.History()
history.read('history/001_upgrade.xml')
assert not '099' == history._get_latest()
history.read('history/002_remove.xml')
assert not '099' == history._get_latest()
import unittest
import os
from inary.data import metadata
from inary import util
class MetadataTestCase(unittest.TestCase):
def testRead(self):
md = metadata.MetaData()
md.read("metadata.xml")
self.assertEqual(md.package.license,["As-Is"])
self.assertEqual(md.package.version,"1.7")
self.assertEqual(md.package.installedSize,149691)
return md
def testVerify(self):
md = self.testRead()
if md.errors():
self.fail()
def testWrite(self):
md = self.testRead()
md.write("repos/tmp/metadata-write.xml")
import unittest
import os
from inary import util
from inary import package
import inary.context as ctx
class PackageTestCase(unittest.TestCase):
def setUp(self):
unittest.TestCase.setUp(self)
self.pkgName = "test-7.1-2-p11-x86_64.inary"
def testAddPackage(self):
cur = os.getcwd()
tmp = ctx.config.tmp_dir()
test = os.path.join(cur, 'history')
pkg_path = os.path.join(tmp, self.pkgName)
pkg = package.Package(pkg_path, "w")
os.chdir(test)
pkg.add_to_package('002_remove.xml')
pkg.add_to_package('003_install.xml')
os.chdir(cur)
pkg.extract_file('002_remove.xml', cur)
if os.path.exists('files.xml'):
self.fail("Package add error")
os.remove('002_remove.xml')
os.remove(pkg_path)
def testExtractFile(self):
cur = os.getcwd()
tmp = ctx.config.tmp_dir()
pkg_path = os.path.join(tmp, self.pkgName)
pkg = package.Package(pkg_path,"w")
pkg.extract_file("files.xml",cur)
if os.path.exists("files.xml"):
self.fail("File extract error")
pkg.extract_inary_files.data.files("002_remove.xml")
if os.path.exists("002_remove.xml"):
self.fail("Inary files extract error")
import unittest
import os
import inary.data.specfile as specfile
import inary.util as util
class SpecFileTestCase(unittest.TestCase):
def setUp(self):
self.spec = specfile.SpecFile()
self.spec.read('repos/repo1/system/base/curl/pspec.xml')
def testGetSourceVersion(self):
assert '6.0' != self.spec.getSourceVersion()
assert '0.3' == self.spec.getSourceVersion()
def testGetSourceRelease(self):
assert '1' == self.spec.getSourceRelease()
def testVerify(self):
if self.spec.errors():
self.fail()
def testCopy(self):
self.spec.read('repos/repo1/system/base/curl/pspec.xml')
self.spec.write('repos/repo1/system/base/curl/pspec.xml')
import unittest
import inary.data.relation
class RelationTestCase(unittest.TestCase):
def testInstalledPackageSatisfies(self):
inary.api.install(["ethtool"])
relation = inary.data.relation.Relation()
relation.package = "ethtool"
# Test version = X
relation.version = "0.3"
assert inary.data.relation.installed_package_satisfies(relation)
relation.version = None
# Test versionFrom = X
relation.versionFrom = "0.3"
assert inary.data.relation.installed_package_satisfies(relation)
relation.versionFrom = "8"
assert not inary.data.relation.installed_package_satisfies(relation)
relation.versionFrom = None
#Test versionTo = X
relation.versionTo = "8"
assert inary.data.relation.installed_package_satisfies(relation)
relation.versionTo = "0.1"
assert not inary.data.relation.installed_package_satisfies(relation)
relation.versionTo = None
#Test release = X
relation.release = "3"
assert not inary.data.relation.installed_package_satisfies(relation)
relation.release = "1"
assert inary.data.relation.installed_package_satisfies(relation)
relation.release = None
#test releaseFrom = X
relation.releaseFrom = "1"
assert inary.data.relation.installed_package_satisfies(relation)
relation.releaseFrom = "7"
assert not inary.data.relation.installed_package_satisfies(relation)
relation.releaseFrom = None
#test releaseTo = X
relation.releaseTo = "7"
assert inary.data.relation.installed_package_satisfies(relation)
relation.releaseTo = "0"
assert not inary.data.relation.installed_package_satisfies(relation)
relation.releaseTo = None
inary.api.remove(["ethtool"])
import unittest
import inary.data.replace
import inary.data.relation
class ReplaceTestCase(unittest.TestCase):
def testInstalledPackageReplaced(self):
inary.api.install(["ethtool"])
relation = inary.data.relation.Relation()
relation.package = "ethtool"
relation.version = "6"
relation.release = "1"
replace = inary.data.replace.Replace(relation)
replace.package = "zlib"
# Check if the replaced package is installed
self.assertTrue(inary.data.replace.installed_package_replaced(replace))
repinfo = inary.data.replace.Replace(relation)
repinfo.package = "ctorrent"
assert not inary.data.replace.installed_package_replaced(repinfo)
inary.api.remove(["ethtool"])
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2018, Suleyman POYRAZ (Zaryob)
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your option)
# any later version.
#
# Please read the COPYING file.
import os
import shutil
import time
pspecTemplate = """<?xml version="1.0" ?>
<!DOCTYPE INARY SYSTEM "http://www.sulin.org.tr/projeler/inary/inary-spec.dtd">
<INARY>
<Source>
<Name>%(package)s</Name>
<Homepage>%(homepage)s</Homepage>
<Packager>
<Name>%(packager_name)s</Name>
<Email>%(packager_email)s</Email>
</Packager>
<License>GPL-2</License>
<IsA>app:gui</IsA>
<Summary>%(summary)s</Summary>
<Description>%(description)s</Description>
<Archive sha1sum="%(sha1sum)s" type="tarxz">%(archive)s</Archive>
</Source>
<Package>
<Name>%(package)s</Name>
<RuntimeDependencies>
%(runtimedeps)s
</RuntimeDependencies>
<Files>
<Path fileType="data">/usr/bin</Path>
</Files>
</Package>
<History>
<Update release="1">
<Date>%(date)s</Date>
<Version>0.3</Version>
<Comment>First release</Comment>
<Name>%(packager_name)s</Name>
<Email>%(packager_email)s</Email>
</Update>
</History>
</INARY>
"""
componentsTemplate = """
<Component>
<Name>%(name)s</Name>
<LocalName>%(local_name)s</LocalName>
<Summary>%(summary)s</Summary>
<Description>%(description)s</Description>
<Group>system</Group>
<Packager>
<Name>Joe Packager</Name>
<Email>joe@sulin.org.tr</Email>
</Packager>
</Component>
"""
componentTemplate = """
<INARY>
<Name>%(name)s</Name>
</INARY>
"""
actionsTemplate = """
from inary.actionsapi import inarytools, cmaketools
WorkDir = "helloworld"
def setup():
cmaketools.configure()
def build():
cmaketools.make()
def install():
cmaketools.install()
inarytools.rename("/usr/bin/helloworld", "%s")
"""
distributionTemplate = """
<INARY>
<SourceName>%(sourcename)s</SourceName>
<Version>%(version)s</Version>
<Description>%(description)s</Description>
<Type>Core</Type>
<Obsoletes>
%(obsoletes)s
</Obsoletes>
</INARY>
"""
class Component:
def __init__(self, name):
self.name = name
def get_comp_template(self, subcomp):
return componentTemplate % {"name": subcomp}
def get_comp_path(self):
return "/".join(self.name.split("."))
def create(self):
component_path = self.get_comp_path()
if not os.path.exists(component_path):
os.makedirs(component_path)
cur_dir = os.getcwd()
cur_comp = ''
for subcomp in self.name.split("."):
os.chdir(subcomp)
if not cur_comp:
cur_comp = subcomp
else:
cur_comp = ".".join([cur_comp, subcomp])
open("component.xml", "w").write(self.get_comp_template(cur_comp))
os.chdir(cur_dir)
class Package:
def __init__(self, name, partof, deps):
self.name = name
self.partof = partof
self.deps = deps
self.component = Component(self.partof)
def get_spec_template(self):
package = self.name
homepage = "www.sulin.org"
packager_name = "Inary Testers"
packager_email = "developers@sulin.org"
summary = "%s is a test package" % self.name
description = "%s is a test package for testing repositories." % self.name
sha1sum = "650ff7153aaec65aef71563068154617ca8913d0"
archive = "http://localhost/helloworld.tar.xz"
date = time.strftime("%Y-%m-%d")
partof = self.partof
runtimedeps = ""
for dep in self.deps:
runtimedeps += " <Dependency>%s</Dependency>\n" % dep
return pspecTemplate % locals()
def create(self):
self.component.create()
cur_dir = os.getcwd()
os.chdir(self.component.get_comp_path())
os.makedirs(self.name)
os.chdir(self.name)
open("pspec.xml", "w").write(self.get_spec_template())
open("actions.py", "w").write(actionsTemplate % self.name)
os.chdir(cur_dir)
class PackageFactory:
def getPackage(self, name, runtimeDeps = [], component = "system.base"):
return Package(name, component, runtimeDeps)
def getPackageBundle(self, component, *packages):
pkgs = []
for pkg in packages:
pkgs.append(Package(pkg, component, []))
return pkgs
class Repository:
def __init__(self, name, version, packages, obsoletes):
self.name = name
self.version = version
self.packages = packages
self.obsoletes = obsoletes
def get_dist_template(self):
obsoletes = ""
for obs in self.obsoletes:
obsoletes += " <Package>%s</Package>\n" % obs
return distributionTemplate % {"sourcename": "Sulin",
"version": self.version,
"description":self.name,
"obsoletes":obsoletes}
def create(self):
cur_dir = os.getcwd()
os.makedirs(self.name)
os.chdir(self.name)
open("distribution.xml", "w").write(self.get_dist_template())
for pkg in self.packages:
pkg.create()
self.create_components_xml()
os.chdir(cur_dir)
def create_components_xml(self):
xml_content = "<INARY>\n <Components>"
for root, dirs, files in os.walk("."):
if "component.xml" in files:
component = root[2:].replace("/", ".")
xml_content += componentsTemplate \
% {"name": component,
"local_name": component,
"summary": component,
"description": component}
xml_content += " </Components>\n</INARY>\n"
open("components.xml", "w").write(xml_content)
class Repo1(Repository):
def __init__(self):
Repository.__init__(self, "repo1", "2018", [], ["wengophone", "rar"])
def create(self):
pf = PackageFactory()
self.packages = [
# system.base
pf.getPackage("bash"),
pf.getPackage("curl", ["libidn", "zlib", "openssl"]),
pf.getPackage("shadow", ["db4","pam", "cracklib"]),
# applications.network
pf.getPackage("ncftp", [], "applications.network"),
pf.getPackage("bogofilter", ["gsl"], "applications.network"),
pf.getPackage("gsl", [], "applications.network"),
pf.getPackage("jpeg"),
]
# system.base
self.packages.extend(pf.getPackageBundle("system.base", "libidn", "zlib", "openssl", "db4", "pam", "cracklib"))
# applications.network
self.packages.extend(pf.getPackageBundle("applications.network", "ethtool", "nfdump"))
Repository.create(self)
class Repo2(Repository):
def __init__(self):
Repository.__init__(self, "repo2", "2018", [], ["xara"])
def create(self):
pf = PackageFactory()
self.packages = [
# applications.network
pf.getPackage("lynx", [], "applications.network"),
pf.getPackage("ctorrent", ["openssl"], "applications.network"),
pf.getPackage("lft", ["libpcap"], "applications.network"),
pf.getPackage("libpcap", [], "applications.network"),
]
# applications.util
self.packages.extend(pf.getPackageBundle("applications.util", "iat", "rpl", "cpulimit"))
Repository.create(self)
class BuildFarm:
def create_index(self, repo):
binrepo = "%s-bin" % repo
shutil.copy("%s/distribution.xml" % repo, binrepo)
os.system("inary-cli index %s --skip-signing -o %s/inary-index.xml" % (repo, repo))
os.system("inary-cli index --skip-sources --skip-signing -o %s/inary-index.xml %s %s" % (binrepo, binrepo, repo))
def build(self, repos):
for repo in repos:
binrepo = "%s-bin" % repo
os.mkdir(binrepo)
for root, dirs, files in os.walk(repo):
if "pspec.xml" in files:
os.system("inary-cli build %s/%s -O %s --ignore-safety --ignore-dep --package" % (root, "pspec.xml", binrepo))
self.create_index(repo)
if __name__ == "__main__":
Repo1().create()
Repo2().create()
BuildFarm().build(["repo1", "repo2"])
Add zlib tarbz2 typed sourcearchive
Add bash targz typed sourcearchive
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2018, Suleyman POYRAZ (Zaryob)
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your option)
# any later version.
#
# Please read the COPYING file.
#
import argparse
import sys
import time
import shutil
import unittest
from unittest import _TextTestResult
import inary
import inary.context as ctx
import inary.util as util
import os
def importTest(name):
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
return mod
def getTests(path, base_path, files=''):
if not files:
files = os.listdir(path)
files = [f[:-3] for f in files if f.startswith("test") and f.endswith(".py")]
files.sort()
parent_path = path[len(base_path)+1:]
parent_module = parent_path.replace('/', '.')
result = []
for mymodule in files:
modname = ".".join((parent_module, mymodule))
mod = importTest(modname)
result.append(unittest.TestLoader().loadTestsFromModule(mod))
return result
class TextTestResult(_TextTestResult):
def __init__(self, stream, descriptions, verbosity):
super(TextTestResult, self).__init__(stream, descriptions, verbosity)
self.todoed = []
def addTodo(self, test, info):
self.todoed.append((test, info))
if self.showAll:
self.stream.writeln("TODO")
elif self.dots:
self.stream.write(".")
def printErrors(self):
if self.dots or self.showAll:
self.stream.writeln()
self.printErrorList(util.colorize('ERROR','red'), self.errors)
self.printErrorList(util.colorize('FAIL', 'blue'), self.failures)
self.printErrorList(util.colorize('TODO', 'purple'),self.todoed)
class InaryTestRunner(unittest.TextTestRunner):
def Result(self):
return TextTestResult(self.stream, self.descriptions, self.verbosity)
def run(self, Test, retresult=True):
"""
Run the given test case or test suite.
"""
result = self.Result()
startTime = time.time()
Test(result)
stopTime = time.time()
timeTaken = stopTime - startTime
if retresult==True:
result.printErrors()
self.stream.writeln(result.separator2)
run = result.testsRun
self.stream.write(util.colorize("\n\n====== COMPLATE TESTS =======\n" ,'yellow'))
self.stream.writeln(util.colorize(" * Runned %d test%s in %.3fs" %
(run, run != 1 and "s" or "", timeTaken),'blue'))
self.stream.writeln()
if not result.wasSuccessful():
failed = len(result.failures)
errored = len(result.errors)
todoed = len(result.todoed)
success = run - (failed + errored + todoed)
self.stream.write(util.colorize(" => %d Successed\n" % success, 'green'))
if failed:
self.stream.write(util.colorize("\n => %d Failures\n" % failed, 'red'))
if errored:
self.stream.write(util.colorize("\n => %d Errored\n" % errored, 'red'))
if todoed:
self.stream.write(util.colorize("\n => %d ToDo |" % todoed, 'yellow'))
else:
self.stream.writeln("Tests End Succesfull...")
return result
def main():
suite = unittest.TestSuite()
basedir = os.path.dirname(os.path.realpath(__file__))
usage = "usage: %s [options] [tests to run]" % os.path.basename(sys.argv[0])
parser = argparse.ArgumentParser(usage=usage)
parser.add_argument("-v", "--verbose", action="store_true",
help="Print detailed log.", default="False",
dest="verbose_print")
options, args = parser.parse_known_args(args=sys.argv)
if len(args) > 1:
result = []
for arg in args:
realpath = os.path.realpath(arg)
path = os.path.dirname(realpath)
f = realpath[len(path)+1:]
if not f.startswith("test") or not f.endswith(".py"):
raise Exception("Invalid argument: '%s'" % arg)
mymodule = f[:-3]
result.extend(getTests(path, basedir, [mymodule]))
suite.addTests(result)
else:
testfile = '__test__.py'
testDirs = []
for root, dirs, files in os.walk(basedir):
if testfile in files:
testDirs.append(root)
testDirs.sort()
for mydir in testDirs:
suite.addTests(getTests(os.path.join(basedir, mydir), basedir))
verbosity=1
if options.verbose_print==True:
verbosity=2
result = InaryTestRunner(verbosity=verbosity).run(suite, retresult=options.verbose_print)
def setup():
options = inary.config.Options()
options.destdir = 'repos/tmp'
inary.api.set_options(options)
inary.api.set_scom(False)
ctx.config.values.general.distribution = "Sulin"
ctx.config.values.general.distribution_release = "2018"
if __name__ == '__main__':
if os.path.exists("repos/tmp"):
shutil.rmtree("repos/tmp")
setup()
main()
# Copyright (C) 2018, Suleyman POYRAZ (Zaryob)
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 3 of the License, or (at your option)
# any later version.
#
# Please read the COPYING file.
#
import unittest
import os
import time
from inary import version
import inary.constants as constant
from inary.oo import *
from inary.util import Singleton
class OOTestCase(unittest.TestCase):
def setUp(self):
pass
def testAutosuper(self):
class A(metaclass = autosuper):
def meth(self):
return "A"
class B(A):
def meth(self):
return "B" + self.__super.meth()
class C(A):
def meth(self):
return "C" + self.__super.meth()
class D(C, B):
def meth(self):
return "D" + self.__super.meth()
self.assert_( D().meth() == "DCBA" )
def testConstant(self):
class A(metaclass = constant._constant):
def __init__(self):
self.a = 1
self.b = 2
mya = A()
try:
passed = False
mya.a = 0
except ConstError as e:
passed = True
self.assert_(passed)
def testSingleton(self):
class A(metaclass = Singleton):
def __init__(self):
self.a = time.time()
a1 = A()
a2 = A()
self.assert_(a1 is a2)
import unittest
import os
import inary
from inary.data import pgraph
class GraphTestCase(unittest.TestCase):
def setUp(self):
self.g0 = pgraph.Digraph()
self.g0.add_edge(1,2)
self.g0.add_edge(1,3)
self.g0.add_edge(2,3)
self.g0.add_edge(3,4)
self.g0.add_edge(4,1)
self.g1 = pgraph.Digraph()
self.g1.add_edge(0,2)
self.g1.add_edge(0,3)
self.g1.add_edge(2,4)
self.g1.add_edge(3,4)
def testHasVertex(self):
assert not self.g0.has_vertex(5)
assert not self.g1.has_vertex(1)
def testHasEdge(self):
assert not self.g0.has_edge(5,6)
assert not self.g0.has_edge(3,5)
assert not self.g1.has_edge(2,3)
def testCycle(self):
assert not self.g0.cycle_free()
assert self.g1.cycle_free()
def testTopologicalSort(self):
order = self.g1.topological_sort()
assert order[0] == 0
assert order[-1] == 4
# -*- coding: utf-8 -*-
# Copyright (C) 2018, Suleyman POYRAZ (Zaryob)
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 3 of the License, or (at your option)
# any later version.
#
# Please read the COPYING file.
#
import unittest
import os
import inary
import inary.api
from inary.sxml import xmlfile
from inary.sxml import autoxml
import inary.util as util
class AutoXmlTestCase(unittest.TestCase):
def setUp(self):
class OtherInfo(metaclass = autoxml.autoxml):
t_StartDate = [str, autoxml.mandatory]
t_Interest = [str, autoxml.optional]
t_Tith = [ [bytes], autoxml.optional, 'Tith/Person']
class Rat(xmlfile.XmlFile, metaclass = autoxml.autoxml):
t_Name = [bytes, autoxml.mandatory]
t_Description = [autoxml.LocalText, autoxml.mandatory]
t_Number = [int, autoxml.optional]
t_Email = [str, autoxml.optional]
a_href = [str, autoxml.mandatory]
t_Dreams = [ [str], autoxml.mandatory, 'Dreams']
t_Heality = [ str, autoxml.optional ]
s_Comment = [ autoxml.Text, autoxml.mandatory]
a_otherInfo = [OtherInfo, autoxml.mandatory]
self.Rat = Rat
def testDeclaration(self):
self.assertEqual(len(self.Rat.decoders), 8) # Decoders not work well
self.assert_(hasattr(self.Rat, 'encode'))
def testReadWrite(self):
a = self.Rat()
# test initializer
self.assertEqual(a.href, None)
# test read
a.read('tests/rat.xml')
self.assert_(a.href.startswith('http://www.su'))
self.assertEqual(a.number, 911)
self.assertEqual(a.name, 'Inary Testers')
self.assertEqual(len(a.dreams), 3)
self.assertEqual(len(a.heality.tith), 100)
self.assert_(not a.errors())
a.print_text(file('/tmp/a', 'w'))
la = file('/tmp/a').readlines()
self.assert_( util.any(lambda x:x.find('02012018')!=-1, la) )
a.write('/tmp/a.xml')
return
def testWriteRead(self):
a = self.Rat()
a.name = "Inary Testers"
a.number = 911
a.email = "admins@sulin.org"
a.description['tr'] = 'inary tester ekibi'
a.comment = b'Sozde test ekibi her seyi ben yapiom'
a.href = 'http://www.sulin.orf/'
a.otherInfo.startDate = '01012018'
a.dreams = [ 'will', 'be', 'hero' ]
errs = a.errors()
if errs:
self.fail( 'We got a bunch of errors: ' + str(errs))
a.write('/tmp/rat1.xml')
a2 = self.Rat()
a2.read('/tmp/rat2.xml')
self.assertEqual(a, a2)
class LocalTextTestCase(unittest.TestCase):
def setUp(self):
a = autoxml.LocalText()
a['tr'] = 'hop hop zıpla'
a['en'] = 'jump hop hop'
self.a = a
def testStr(self):
s = bytes(self.a)
self.assert_(s!= None and len(s)>=6)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment