// **********************************************************************
//
// Copyright (c) 1999
// Object Oriented Concepts, Inc.
// Billerica, MA, USA
//
// All Rights Reserved
//
// **********************************************************************

#include <assert.h>
#include <stdlib.h>
#include <string.h>

#include <OB/CORBA.h>
#include <OB/Util.h>

#include <OB/CosNaming.h>

#include "TestMacro.h"


//
// Test CosNaming_NamingContextExt::to_name()
//
void
TestToName(CORBA_ORB_ptr orb, CosNaming_NamingContextExt_ptr root)
{
    CosNaming_Name_var name;
    CosNaming_NamingContextExt::StringName_var str;

    //
    // Test name components with both ID and Kind field
    //
    str = CORBA_string_dup("first.node/second.node");
    SUCCEED(name = root -> to_name(str));
    assert(name -> length() == 2);
    assert(strcmp(name[0].id, "first") == 0 &&
	   strcmp(name[0].kind, "node") == 0);
    assert(strcmp(name[1].id, "second") == 0 &&
	   strcmp(name[1].kind, "node") == 0);

    //
    // Test name components with missing Kind field
    //
    str = CORBA_string_dup("first.node/second");
    SUCCEED(name = root -> to_name(str));
    assert(name -> length() == 2);
    assert(strcmp(name[0].id, "first") == 0 &&
	   strcmp(name[0].kind, "node") == 0);
    assert(strcmp(name[1].id, "second") == 0 &&
	   strcmp(name[1].kind, "") == 0);

    //
    // Test name components with missing ID field
    //
    str = CORBA_string_dup("first.node/.node");
    SUCCEED(name = root -> to_name(str));
    assert(name -> length() == 2);
    assert(strcmp(name[0].id, "first") == 0 &&
	   strcmp(name[0].kind, "node") == 0);
    assert(strcmp(name[1].id, "") == 0 &&
	   strcmp(name[1].kind, "node") == 0);

    //
    // Test node with empty ID and Kind field
    //
    str = CORBA_string_dup("first.node//third.node");
    SUCCEED(name = root -> to_name(str));
    assert(name -> length() == 3);
    assert(strcmp(name[0].id, "first") == 0 &&
	   strcmp(name[0].kind, "node") == 0);
    assert(strcmp(name[1].id, "") == 0 &&
	   strcmp(name[1].kind, "") == 0);
    assert(strcmp(name[2].id, "third") == 0 &&
	   strcmp(name[2].kind, "node") == 0);

    //
    // Test nodes with characters that are escaped
    //
    str =  CORBA_string_dup(
	"first.node\\.bla/second\\/bla.node/third.\\\\node");
    SUCCEED(name = root -> to_name(str));
    assert(name -> length() == 3);
    assert(strcmp(name[0].id, "first") == 0 &&
	   strcmp(name[0].kind, "node.bla") == 0);
    assert(strcmp(name[1].id, "second/bla") == 0 &&
	   strcmp(name[1].kind, "node") == 0);
    assert(strcmp(name[2].id, "third") == 0 &&
	   strcmp(name[2].kind, "\\node") == 0);

    //
    // Test empty name
    //
    try
    {
	str = CORBA_string_dup("");
	name = root -> to_name(str);
	assert("to_name should not have succeeded" == 0);
    }
    catch(const CosNaming_NamingContext::InvalidName&)
    {
	// Expected
    }
}
