TEST (test_contextual_policy, root) { using namespace kdb; KeySet ks; ks.append (Key ("user/available", KEY_VALUE, "12", KEY_END)); Context c; // clang-format off ContextualValue<int, GetPolicyIs<MyDynamicGetPolicy>> cv (ks, c, Key("/", KEY_CASCADING_NAME, KEY_META, "default", "88", KEY_META, "override/#0", "user/available", KEY_END)); // clang-format on EXPECT_EQ (cv, 12); EXPECT_EQ (cv, cv); cv = 40; EXPECT_EQ (cv, 40); c.activate<RootLayer> (); EXPECT_EQ (cv, 40); ContextualValue<int, GetPolicyIs<MyDynamicGetPolicy>> cv2 (cv); EXPECT_EQ (cv, cv2); }
TEST(type, version) { try { KeySet config; config.append( Key("system/require_version", KEY_VALUE, "3", KEY_END) ); TypeChecker tc(config); succeed_if (false, "version should not match"); } catch (const char *text) { succeed_if (true, "version should not match"); succeed_if (!strcmp(text, "Required Version does not match 2"), "failed version text does not match"); } try { KeySet config; config.append( Key("system/require_version", KEY_VALUE, "2", KEY_END) ); TypeChecker tc(config); succeed_if (true, "version should match"); } catch (const char *text) { succeed_if (false, "version should match"); } }
TEST (test_contextual_policy, setPolicy) { using namespace kdb; KeySet ks; Context c; // clang-format off ContextualValue<int, SetPolicyIs<MySetPolicy<int>>> cv (ks, c, Key("/test", KEY_CASCADING_NAME, KEY_VALUE, "/test", KEY_META, "default", "88", KEY_END)); // clang-format on EXPECT_EQ (cv, 88); EXPECT_EQ (cv, 88); EXPECT_TRUE (ks.lookup ("/test")) << "did not find /test"; EXPECT_FALSE (ks.lookup ("dir/test")) << "found dir/test wrongly"; cv = 40; EXPECT_EQ (cv, 40); cv.syncKeySet (); EXPECT_EQ (cv, 40); // TODO: setPolicy not working correctly EXPECT_TRUE (ks.lookup ("/test")) << "did not find /test"; EXPECT_TRUE (ks.lookup ("dir/test")) << "could not find dir/test"; }
/** * @brief give info about current mounted backends * * @param mountConf a keyset that contains everything below * Backends::mountpointsPath * * @return an vector of information about mounted backends */ Backends::BackendInfoVector Backends::getBackendInfo (KeySet mountConf) { std::vector<BackendInfo> ret; Key rootKey (Backends::mountpointsPath, KEY_END); Key cur; mountConf.rewind (); while ((cur = mountConf.next ())) { if (cur.isDirectBelow (rootKey)) { BackendInfo bi; Key path = mountConf.lookup (cur.getName () + "/config/path"); if (path) { bi.path = path.getString (); } Key mp = mountConf.lookup (cur.getName () + "/mountpoint"); if (mp) { bi.mountpoint = mp.getString (); } bi.name = cur.getBaseName (); ret.push_back (bi); } } return ret; }
int MetaRemoveCommand::execute (Cmdline const & cl) { if (cl.arguments.size () != 2) { throw invalid_argument ("Need 2 arguments"); } Key parentKey = cl.createKey (0); string metaname = cl.arguments[1]; KeySet conf; kdb.get (conf, parentKey); printWarnings (cerr, parentKey); Key k = conf.lookup (parentKey); if (!k) { cerr << "Key not found" << endl; return 1; } k.delMeta (metaname); kdb.set (conf, parentKey); return 0; }
/* ************************************************************************* */ GaussianFactorGraph::Keys GaussianFactorGraph::keys() const { KeySet keys; BOOST_FOREACH(const sharedFactor& factor, *this) if (factor) keys.insert(factor->begin(), factor->end()); return keys; }
kdb::Key mountBackend (int iteration) { using namespace kdb; using namespace kdb::tools; Key mp = getMountpointForIteration<VARIANT> (iteration); std::string cf = "benchmark_" + plugin_variant_names[VARIANT] + "_" + std::to_string (iteration) + ".ecf"; unlink (cf.c_str ()); KDB kdb; KeySet mountConfig; kdb.get (mountConfig, "system/elektra/mountpoints"); MountBackendBuilder b; b.setMountpoint (mp, KeySet (0, KS_END)); b.addPlugin (PluginSpec ("resolver")); b.useConfigFile (cf); b.addPlugin (PluginSpec ("dump")); if (VARIANT != NO_CRYPTO) { KeySet pluginConfig; pluginConfig.append (Key ("user/encrypt/key", KEY_VALUE, GPG_TEST_KEY_ID, KEY_END)); pluginConfig.append (Key ("user/gpg/unit_test", KEY_VALUE, "1", KEY_END)); b.addPlugin (PluginSpec (plugin_variant_names[VARIANT], pluginConfig)); } b.validated (); b.serialize (mountConfig); kdb.set (mountConfig, "system/elektra/mountpoints"); kdb.close (); return mp; }
MergeResult ThreeWayMerge::mergeKeySet (const MergeTask & task) { MergeResult result; detectConflicts (task, result); detectConflicts (task.reverse (), result, true); if (!result.hasConflicts ()) return result; // TODO: test this behaviour (would probably need mocks) Key current; KeySet conflicts = result.getConflictSet (); conflicts.rewind (); while ((current = conflicts.next ())) { for (auto & elem : strategies) { (elem)->resolveConflict (task, current, result); if (!result.isConflict (current)) break; } } return result; }
void TestCommand::doBasicTest () { { KDB kdb; Key t = root.dup (); t.addBaseName ("basic"); t.setString ("BasicString"); KeySet basic; basic.append (t); KeySet test; kdb.get (test, root); kdb.set (basic, root); } { KDB kdb; Key t = root.dup (); t.addBaseName ("basic"); t.setString ("BasicString"); KeySet test; kdb.get (test, root); nrTest++; if (!test.lookup (t)) { nrError++; cerr << "Basic test failed" << endl; } } }
int GetCommand::execute (Cmdline const & cl) { if (cl.arguments.size () != 1) throw invalid_argument ("Need one argument"); KeySet conf; kdb::Key root = cl.createKey (0); kdb::KDB kdb (root); std::string n; if (cl.all) { n = root.getName (); root.setName ("/"); } kdb.get (conf, root); if (cl.all) { root.setName (n); } // do a lookup without tracer to warm up default cache conf.lookup (root); root.setCallback (warnOnMeta); if (cl.verbose) { cout << "got " << conf.size () << " keys" << std::endl; root.setCallback (printTrace); } Key k = conf.lookup (root); int ret = 0; if (k) { if (cl.verbose) { cout << "The resulting keyname is " << k.getName () << std::endl; } cout << k.getString (); } else { cerr << "Did not find key"; ret = 1; } if (!cl.noNewline) { cout << endl; } printWarnings (cerr, root); printError (cerr, root); return ret; }
TypeChecker(KeySet config) { enforce = config.lookup("/enforce"); Key k = config.lookup("/require_version"); if (k && k.getString() != "2") throw "Required Version does not match 2"; types.insert (pair<string, Type*>("short", new MType<kdb::short_t>())); types.insert (pair<string, Type*>("unsigned_short", new MType<kdb::unsigned_short_t>())); types.insert (pair<string, Type*>("long", new MType<kdb::long_t>())); types.insert (pair<string, Type*>("unsigned_long", new MType<kdb::unsigned_long_t>())); types.insert (pair<string, Type*>("long_long", new MType<kdb::long_long_t>())); types.insert (pair<string, Type*>("unsigned_long_long", new MType<kdb::unsigned_long_long_t>())); types.insert (pair<string, Type*>("float", new TType<kdb::float_t>())); types.insert (pair<string, Type*>("double", new TType<kdb::double_t>())); types.insert (pair<string, Type*>("long_double", new TType<kdb::long_double_t>())); types.insert (pair<string, Type*>("char", new TType<kdb::char_t>())); types.insert (pair<string, Type*>("boolean", new TType<kdb::boolean_t>())); types.insert (pair<string, Type*>("octet", new TType<kdb::octet_t>())); // non-standard types (deprecated, just for // compatibility): types.insert (pair<string, Type*>("any", new AnyType())); types.insert (pair<string, Type*>("empty", new EmptyType())); types.insert (pair<string, Type*>("FSType", new FSType())); types.insert (pair<string, Type*>("string", new StringType())); }
void RemountCommand::cloneMountpoint(Cmdline const & cl) { Key existingParent (Backends::getBasePath(existingName), KEY_END); Key newParent (Backends::getBasePath(mp), KEY_END); KeySet existingBackend = mountConf.cut(existingParent); mountConf.append(existingBackend); KeySet newBackend(existingBackend.size(), KS_END); string configPath = newParent.getName() + "/config/path"; string mpPath = newParent.getName() + "/mountpoint"; existingBackend.rewind(); while (Key current = existingBackend.next()) { Key newKey = rebaseKey (current, existingParent, newParent); newBackend.append(newKey); if (newKey.getName() == mpPath) { newKey.setString(mp); } if (newKey.getName() == configPath) { newKey.setString(cl.arguments[0]); } } mountConf.append(newBackend); }
int main () { using namespace kdb; std::vector<Key> vc; vc.push_back (Key ("user/key3/1", KEY_META, "order", "2", KEY_END)); vc.push_back (Key ("user/begin", KEY_META, "order", "1", KEY_END)); vc.push_back (Key ("user/key3/4", KEY_META, "order", "3", KEY_END)); vc.push_back (Key ("user/key3/dup", KEY_META, "order", "4", KEY_END)); vc.push_back (Key ("user/key3/dup", KEY_END)); vc.push_back (Key ("user/unordered", KEY_END)); vc.push_back (Key ("user/end", KEY_META, "order", "5", KEY_END)); std::sort (vc.begin (), vc.end (), keyOrder); KeySet ks (20, KS_END); std::cout << "Our Vector with special ordering:" << std::endl; for (auto k : vc) { std::cout << k.getName () << std::endl; ks.append (k); } // now we have a keyset (of course again with KeySet ordering and // duplicates removed. std::cout << "\nNow KeySet:" << std::endl; for (auto && ks_i : ks) { Key k (ks_i); std::cout << k.getName () << std::endl; } }
int LsCommand::execute (Cmdline const & cl) { if (cl.arguments.size () != 1) { throw invalid_argument ("1 argument required"); } printWarnings (cerr, root); root = cl.createKey (0); kdb.get (ks, root); if (cl.verbose) cout << "size of all keys in mountpoint: " << ks.size () << endl; KeySet part (ks.cut (root)); if (cl.verbose) cout << "size of requested keys: " << part.size () << endl; cout.setf (std::ios_base::unitbuf); if (cl.null) { cout.unsetf (std::ios_base::skipws); } cout << part; printWarnings (cerr, root); return 0; }
MergeResult ThreeWayMerge::mergeKeySet(const MergeTask& task) { MergeResult result; detectConflicts (task, result); detectConflicts (task.reverse (), result, true); if (!result.hasConflicts()) return result; // TODO: test this behaviour (would probably need mocks) Key current; KeySet conflicts = result.getConflictSet(); conflicts.rewind(); while ((current = conflicts.next ())) { for (vector<MergeConflictStrategy *>::iterator it = strategies.begin (); it != strategies.end (); ++it) { (*it)->resolveConflict (task, current, result); if (!result.isConflict(current)) break; } } return result; }
int LsCommand::execute (Cmdline const & cl) { checkArguments (cl); printWarnings (cerr, root); root = cl.createKey (0); kdb.get (ks, root); if (cl.verbose) cout << "size of all keys in mountpoint: " << ks.size () << endl; KeySet part (ks.cut (root)); if (cl.verbose) cout << "size of requested keys: " << part.size () << endl; cout.setf (std::ios_base::unitbuf); if (cl.null) { cout.unsetf (std::ios_base::skipws); } printResults (part, getDepth (root), cl); printWarnings (cerr, root); return 0; }
int CpCommand::execute (Cmdline const & cl) { if (cl.arguments.size () != 2) { throw invalid_argument ("wrong number of arguments, 2 needed"); } KeySet conf; Key sourceKey = cl.createKey (0); if (!sourceKey.isValid ()) { throw invalid_argument ("Source given is not a valid keyname"); } Key destKey = cl.createKey (1); if (!destKey.isValid ()) { throw invalid_argument ("Destination given is not a valid keyname"); } string newDirName = destKey.getName (); kdb.get (conf, sourceKey); kdb.get (conf, destKey); KeySet tmpConf = conf; KeySet oldConf; oldConf.append (tmpConf.cut (sourceKey)); KeySet newConf; oldConf.rewind (); std::string sourceName = sourceKey.getName (); if (cl.verbose) cout << "common name: " << sourceName << endl; if (cl.recursive) { // copy all keys with new name Key k; while ((k = oldConf.next ())) { Key rk = rename_key (k, sourceName, newDirName, cl.verbose); copySingleKey (cl, rk, tmpConf, newConf); } } else { // just copy one key Key k = oldConf.next (); Key rk = rename_key (k, sourceName, newDirName, cl.verbose); copySingleKey (cl, rk, tmpConf, newConf); } newConf.append (tmpConf); // these are unrelated keys newConf.append (oldConf); // these are the original keys newConf.rewind (); kdb.set (newConf, destKey); return 0; }
/** * @brief Add all keys of a keyset * * Will not update the underlying keyset (is fixed at * construction) * * @param ks */ void add(KeySet const & ks) { for (KeySet::iterator it = ks.begin(); it != ks.end(); ++it) { add(*it); } }
std::vector<PluginSpec> PluginVariantDatabase::getPluginVariantsFromGenconf (PluginSpec const & whichplugin, KeySet const & genconf, KeySet const & sysconf) const { std::vector<PluginSpec> result; KeySet ksToIterate (genconf); for (auto kCurrent : ksToIterate) { Key kCurrentTest (kCurrent.getNamespace () + "/", KEY_END); kCurrentTest.addBaseName (kCurrent.getBaseName ()); // e.g. system/space if (kCurrentTest == kCurrent) { PluginSpec variant (whichplugin); KeySet ksVariantConfToAdd; // new base for plugin conf Key kVariantPluginConf ("system/", KEY_END); // take variant config from genconf and transform it to proper plugin conf, // e.g. system/space/config/format -> system/format Key kVariantConf (kCurrentTest); kVariantConf.addBaseName ("config"); // e.g. system/space/config this->addKeysBelowKeyToConf (kVariantConf, genconf, kVariantPluginConf, ksVariantConfToAdd); // TODO plugin infos // check if the variant was disabled : system/elektra/plugins/simpleini/variants/space/disable Key kDisable = sysconf.lookup (this->buildVariantSysconfKey (whichplugin, kCurrent.getBaseName (), "disable")); if (kDisable && kDisable.getString () == "1") { continue; // skip this variant } // check if an override is available : system/elektra/plugins/simpleini/variants/space/override Key kOverride = sysconf.lookup (this->buildVariantSysconfKey (whichplugin, kCurrent.getBaseName (), "override")); if (kOverride && kOverride.getString () == "1") { // first delete config from genconf entirely ksVariantConfToAdd.clear (); Key kVariantSysconf (this->buildVariantSysconfKey (whichplugin, kCurrent.getBaseName (), "config")); this->addKeysBelowKeyToConf (kVariantSysconf, sysconf, kVariantPluginConf, ksVariantConfToAdd); } if (ksVariantConfToAdd.size () == 0) { continue; // no config means no variant } variant.appendConfig (ksVariantConfToAdd); result.push_back (variant); } } std::vector<PluginSpec> resFromSysconf (this->getPluginVariantsFromSysconf (whichplugin, sysconf, genconf)); result.insert (result.end (), resFromSysconf.begin (), resFromSysconf.end ()); return result; }
TEST_F (Simple, WrongParent) { using namespace kdb; KDB kdb; Key parent ("meta", KEY_META_NAME, KEY_END); KeySet ks; EXPECT_THROW (kdb.set (ks, parent), kdb::KDBException); ASSERT_EQ (ks.size (), 0) << "got keys from freshly mounted backends" << ks; }
TEST_F (Simple, WrongStateCascading) { using namespace kdb; KDB kdb; KeySet ks; Key parentKey (testRoot, KEY_END); EXPECT_THROW (kdb.set (ks, parentKey), kdb::KDBException) << "kdb set without prior kdb get should have 107 Wrong State"; ASSERT_EQ (ks.size (), 0) << "got keys from freshly mounted backends" << ks; }
void TestCommand::doStringTest () { vector<string> teststrings; teststrings.push_back (""); teststrings.push_back ("value"); teststrings.push_back ("value with spaces"); teststrings.push_back (" a very long value with many spaces and basically very very long, but only text ... "); for (int i = 1; i < 256; ++i) teststrings.back () += " very very long, but only text ... "; for (auto & teststring : teststrings) { { KDB kdb; Key t = root.dup (); t.addBaseName ("string"); t.setString (teststring); KeySet basic; basic.append (t); KeySet test; kdb.get (test, root); kdb.set (basic, root); } { KDB kdb; KeySet test; kdb.get (test, root); Key t = root.dup (); t.addBaseName ("string"); Key res = test.lookup (t); nrTest++; if (!res) { nrError++; cerr << "String test failed (key not found)" << t.getName () << endl; continue; } nrTest++; if (res.getString () != teststring) { nrError++; cerr << "String test failed (value is not equal)" << endl; cerr << "We got: \"" << res.getString () << "\"" << endl; cerr << "We wanted: \"" << teststring << "\"" << endl; } } } }
Point operator() (KeySet const & ks, std::string const & name, option_t const options) const { Key x = ks.lookup (name + "/x", options); if (!x) throw KeyNotFoundException (name + "/x not found"); Key y = ks.lookup (name + "/y", options); if (!y) throw KeyNotFoundException (name + "/y not found"); return Point (x.get<int> (), y.get<int> ()); }
/* ************************************************************************* */ TEST(Marginals, order) { NonlinearFactorGraph fg; fg += PriorFactor<Pose2>(0, Pose2(), noiseModel::Unit::Create(3)); fg += BetweenFactor<Pose2>(0, 1, Pose2(1,0,0), noiseModel::Unit::Create(3)); fg += BetweenFactor<Pose2>(1, 2, Pose2(1,0,0), noiseModel::Unit::Create(3)); fg += BetweenFactor<Pose2>(2, 3, Pose2(1,0,0), noiseModel::Unit::Create(3)); Values vals; vals.insert(0, Pose2()); vals.insert(1, Pose2(1,0,0)); vals.insert(2, Pose2(2,0,0)); vals.insert(3, Pose2(3,0,0)); vals.insert(100, Point2(0,1)); vals.insert(101, Point2(1,1)); fg += BearingRangeFactor<Pose2,Point2>(0, 100, vals.at<Pose2>(0).bearing(vals.at<Point2>(100)), vals.at<Pose2>(0).range(vals.at<Point2>(100)), noiseModel::Unit::Create(2)); fg += BearingRangeFactor<Pose2,Point2>(0, 101, vals.at<Pose2>(0).bearing(vals.at<Point2>(101)), vals.at<Pose2>(0).range(vals.at<Point2>(101)), noiseModel::Unit::Create(2)); fg += BearingRangeFactor<Pose2,Point2>(1, 100, vals.at<Pose2>(1).bearing(vals.at<Point2>(100)), vals.at<Pose2>(1).range(vals.at<Point2>(100)), noiseModel::Unit::Create(2)); fg += BearingRangeFactor<Pose2,Point2>(1, 101, vals.at<Pose2>(1).bearing(vals.at<Point2>(101)), vals.at<Pose2>(1).range(vals.at<Point2>(101)), noiseModel::Unit::Create(2)); fg += BearingRangeFactor<Pose2,Point2>(2, 100, vals.at<Pose2>(2).bearing(vals.at<Point2>(100)), vals.at<Pose2>(2).range(vals.at<Point2>(100)), noiseModel::Unit::Create(2)); fg += BearingRangeFactor<Pose2,Point2>(2, 101, vals.at<Pose2>(2).bearing(vals.at<Point2>(101)), vals.at<Pose2>(2).range(vals.at<Point2>(101)), noiseModel::Unit::Create(2)); fg += BearingRangeFactor<Pose2,Point2>(3, 100, vals.at<Pose2>(3).bearing(vals.at<Point2>(100)), vals.at<Pose2>(3).range(vals.at<Point2>(100)), noiseModel::Unit::Create(2)); fg += BearingRangeFactor<Pose2,Point2>(3, 101, vals.at<Pose2>(3).bearing(vals.at<Point2>(101)), vals.at<Pose2>(3).range(vals.at<Point2>(101)), noiseModel::Unit::Create(2)); Marginals marginals(fg, vals); KeySet set = fg.keys(); FastVector<Key> keys(set.begin(), set.end()); JointMarginal joint = marginals.jointMarginalCovariance(keys); LONGS_EQUAL(3, (long)joint(0,0).rows()); LONGS_EQUAL(3, (long)joint(1,1).rows()); LONGS_EQUAL(3, (long)joint(2,2).rows()); LONGS_EQUAL(3, (long)joint(3,3).rows()); LONGS_EQUAL(2, (long)joint(100,100).rows()); LONGS_EQUAL(2, (long)joint(101,101).rows()); }
void PluginVariantDatabase::addKeysBelowKeyToConf (Key const & below, KeySet const & conf, Key const & newbase, KeySet & targetconf) const { KeySet confCp (conf); KeySet ksVariantSysConf = confCp.cut (below); for (auto kVariantCurrent : ksVariantSysConf) { if (!kVariantCurrent.isBelow (below)) continue; targetconf.append (helper::rebaseKey (kVariantCurrent, below, newbase)); } }
TEST_F(ThreeWayMergeTest, EqualKeySetsMerge) { MergeResult result = merger.mergeKeySet (base, ours, theirs, mergeParent); EXPECT_FALSE(result.hasConflicts()) << "Invalid conflict detected"; KeySet merged = result.getMergedKeys (); EXPECT_EQ(5, merged.size ()); compareAllKeys (merged); }
TEST_F (Simple, GetNothing) { using namespace kdb; KDB kdb; KeySet ks; kdb.get (ks, testRoot); ASSERT_EQ (ks.size (), 0) << "got keys from freshly mounted backends" << ks; struct stat buf; ASSERT_EQ (stat (mp->systemConfigFile.c_str (), &buf), -1) << "found wrong file"; }
TEST (MergeResult, IsConflictWorks) { Key conflictKey = Key ("user/test/config/key1", KEY_END); KeySet conflicts; conflicts.append (conflictKey); KeySet merged; MergeResult result (conflicts, merged); EXPECT_TRUE (result.isConflict (conflictKey)); EXPECT_FALSE (result.isConflict (Key ("user/test/config/key2", KEY_END))); }
int MetaSetCommand::execute (Cmdline const & cl) { if (cl.arguments.size () < 2 || cl.arguments.size () > 3) { throw invalid_argument ("Need 2 or 3 arguments"); } string metaname = cl.arguments[1]; Key parentKey = cl.createKey (0); string keyname = parentKey.getName (); if (keyname[0] == '/') { // fix name for lookup keyname = "spec" + keyname; if (!cl.quiet) std::cout << "Using keyname " << keyname << std::endl; // fix k for kdb.set later parentKey.setName (keyname); } KeySet conf; kdb.get (conf, parentKey); Key k = conf.lookup (parentKey); if (!k) { k = Key (keyname, KEY_END); // k.setBinary(0, 0); // conceptually maybe better, but would have confusing "binary" metadata conf.append (k); if (cl.verbose) cout << "Creating key " << keyname << endl; } if (!k.isValid ()) { cerr << "Could not create key " << keyname << endl; return 1; } if (cl.arguments.size () == 2) { if (!cl.quiet) cout << "Only two arguments, thus deleting metaname " << metaname << endl; k.delMeta (metaname); } else { std::string metavalue = cl.arguments[2]; if (metaname == "atime" || metaname == "mtime" || metaname == "ctime") { stringstream str (metavalue); time_t t; str >> t; if (!str.good ()) throw "conversion failure"; k.setMeta<time_t> (metaname, t); } else {
MergeResult ThreeWayMerge::mergeKeySet (const KeySet & base, const KeySet & ours, const KeySet & theirs, const Key & mergeRoot) { Key ourkey = ours.head ().dup (); Key theirkey = theirs.head ().dup (); Key basekey = base.head ().dup (); MergeResult merged = mergeKeySet ( MergeTask (BaseMergeKeys (base, basekey), OurMergeKeys (ours, ourkey), TheirMergeKeys (theirs, theirkey), mergeRoot)); return merged; }