1979/tests/test_map.py

tests / test_map.py

tests/test_map.py · 11.6 KB

# -*- coding: utf-8 -*-
"""Test Map - 地图系统测试

覆盖:节点初始化/驻军/动态棋子/连接/寻路/情报/城市易手
"""

import pytest
import sys
import os

sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src'))

from map import (
    Map, MapNode, Garrison, FactionUnit, Intelligence,
    CONTROL_STATES, INITIAL_GARRISONS, CONNECTIONS,
)


class TestMapNode:
    """测试节点类。"""

    def test_node_creation(self):
        node = MapNode('测试城', 3, 45.0, 126.0)
        assert node.name == '测试城'
        assert node.level == 3
        assert node.x == 45.0
        assert node.y == 126.0
        assert node.connections == []
        assert node.garrison is None
        assert node.control is None

    def test_add_connection(self):
        node = MapNode('A', 3, 0, 0)
        node.add_connection('B', '国道')
        assert ('B', '国道') in node.connections
        # 重复添加不重复
        node.add_connection('B', '国道')
        assert len(node.connections) == 1

    def test_get_control_state_no_garrison(self):
        node = MapNode('A', 3, 0, 0)
        assert node.get_control_state() == '无人区'
        node.control = 'pla'
        assert node.get_control_state() == '解放军控制'

    def test_get_control_state_with_garrison(self):
        node = MapNode('A', 3, 0, 0)
        node.garrison = Garrison('soviet', 100)
        assert node.get_control_state() == '苏军控制'


class TestGarrison:
    """测试驻军类。"""

    def test_garrison_creation(self):
        g = Garrison('pla', 150, 0.8)
        assert g.faction == 'pla'
        assert g.strength == 150
        assert g.morale == 0.8
        assert g.alive is True

    def test_garrison_zero_strength(self):
        g = Garrison('bandit', 0)
        assert g.alive is False

    def test_take_damage(self):
        g = Garrison('pla', 100)
        defeated = g.take_damage(30)
        assert g.strength == 70
        assert not defeated

    def test_take_damage_defeated(self):
        g = Garrison('pla', 50)
        defeated = g.take_damage(60)
        assert g.strength == 0
        assert g.alive is False
        assert defeated


class TestFactionUnit:
    """测试动态棋子类。"""

    def test_creation(self):
        unit = FactionUnit('测试队', 'bandit', 60, 40, '沈阳', '铁岭')
        assert unit.name == '测试队'
        assert unit.faction == 'bandit'
        assert unit.strength == 60
        assert unit.speed == 40
        assert unit.current_node == '沈阳'
        assert unit.target == '铁岭'
        assert unit.alive is True

    def test_decide_move(self):
        unit = FactionUnit('测试队', 'bandit', 60, 40, '沈阳')
        graph = {'沈阳': [('铁岭', '国道'), ('辽阳', '国道'), ('抚顺', '国道')]}
        target = unit.decide_move(graph)
        assert target in ['铁岭', '辽阳', '抚顺']
        assert unit.target == target

    def test_decide_move_no_neighbors(self):
        unit = FactionUnit('测试队', 'bandit', 60, 40, '孤岛')
        graph = {'孤岛': []}
        target = unit.decide_move(graph)
        assert target is None

    def test_move(self):
        unit = FactionUnit('测试队', 'bandit', 60, 40, '沈阳', '铁岭')
        graph = {'沈阳': [('铁岭', '国道')], '铁岭': [('沈阳', '国道')]}
        new_pos = unit.move(graph)
        assert new_pos == '铁岭'
        assert unit.current_node == '铁岭'

    def test_attack_garrison_victory(self):
        unit = FactionUnit('测试队', 'bandit', 500, 40, '沈阳')
        garrison = Garrison('pla', 10, 0.1)
        result = unit.attack_garrison(garrison)
        # 高战力应该能击败低战力
        assert result is True

    def test_attack_garrison_empty(self):
        unit = FactionUnit('测试队', 'bandit', 60, 40, '沈阳')
        result = unit.attack_garrison(None)
        assert result is True


class TestIntelligence:
    """测试情报系统。"""

    def test_add_report(self):
        intel = Intelligence()
        intel.add_report('沈阳', 'pla', 0.9, '侦察')
        assert '沈阳' in intel.reports
        assert intel.reports['沈阳']['control'] == 'pla'
        assert intel.reports['沈阳']['accuracy'] == 0.9
        assert intel.reports['沈阳']['days_old'] == 0

    def test_get_intel(self):
        intel = Intelligence()
        intel.add_report('沈阳', 'pla', 0.9, '侦察')
        report = intel.get_intel('沈阳')
        assert report is not None
        assert report['control'] == 'pla'
        assert report['effective_accuracy'] == 0.9

    def test_get_intel_unknown(self):
        intel = Intelligence()
        report = intel.get_intel('未知城')
        assert report is None

    def test_tick(self):
        intel = Intelligence()
        intel.add_report('沈阳', 'pla', 0.9, '侦察')
        intel.tick()
        report = intel.get_intel('沈阳')
        assert report['days_old'] == 1
        # 时效衰减:每天降低5%
        assert report['effective_accuracy'] == 0.85

    def test_tick_multiple_days(self):
        intel = Intelligence()
        intel.add_report('沈阳', 'pla', 0.9, '侦察')
        for _ in range(5):
            intel.tick()
        report = intel.get_intel('沈阳')
        assert report['days_old'] == 5
        assert report['effective_accuracy'] == 0.65  # 0.9 - 5*0.05 = 0.65

    def test_get_known_nodes(self):
        intel = Intelligence()
        intel.add_report('沈阳', 'pla', 0.9, '侦察')
        intel.add_report('大连', 'pla', 0.8, '侦察')
        nodes = intel.get_known_nodes()
        assert len(nodes) == 2
        assert '沈阳' in nodes
        assert '大连' in nodes


class TestMap:
    """测试地图类。"""

    def test_map_creation(self):
        game_map = Map()
        assert len(game_map.nodes) > 0
        assert len(game_map.faction_units) > 0

    def test_nodes_have_connections(self):
        game_map = Map()
        # 每个节点至少3条出路(排除边界节点)
        for name, node in game_map.nodes.items():
            if name in ('漠河', '满洲里', '山海关', '秦皇岛', '承德'):
                continue  # 边界节点可能连接较少
            assert len(node.connections) >= 1, f"{name} 没有连接"

    def test_each_node_at_least_one_connection(self):
        game_map = Map()
        for name, node in game_map.nodes.items():
            assert len(node.connections) >= 1, f"{name} 没有任何连接"

    def test_connections_bidirectional(self):
        game_map = Map()
        for name, node in game_map.nodes.items():
            for target, road_type in node.connections:
                if target in game_map.nodes:
                    back_refs = [t for t, _ in game_map.nodes[target].connections]
                    assert name in back_refs, f"{name} -> {target} 不是双向连接"

    def test_initial_garrisons(self):
        game_map = Map()
        for name, (faction, strength) in INITIAL_GARRISONS.items():
            if name in game_map.nodes and faction:
                assert game_map.nodes[name].garrison is not None
                assert game_map.nodes[name].garrison.faction == faction
                assert game_map.nodes[name].garrison.strength == strength

    def test_faction_units_alive(self):
        game_map = Map()
        for unit in game_map.faction_units:
            assert unit.alive is True
            assert unit.current_node is not None

    def test_get_node_status(self):
        game_map = Map()
        status = game_map.get_node_status('沈阳')
        assert status is not None
        assert status['name'] == '沈阳'
        assert status['level'] == 1  # 省会
        assert status['garrison_strength'] > 0
        assert status['garrison_faction'] == 'pla'

    def test_get_node_status_unknown(self):
        game_map = Map()
        status = game_map.get_node_status('不存在')
        assert status is None

    def test_get_route_direct(self):
        game_map = Map()
        route = game_map.get_route('大连', '瓦房店')
        assert route == ['大连', '瓦房店']

    def test_get_route_multi_hop(self):
        game_map = Map()
        route = game_map.get_route('大连', '沈阳')
        assert len(route) > 2
        assert route[0] == '大连'
        assert route[-1] == '沈阳'

    def test_get_route_same_node(self):
        game_map = Map()
        route = game_map.get_route('沈阳', '沈阳')
        assert route == ['沈阳']

    def test_get_route_unknown(self):
        game_map = Map()
        route = game_map.get_route('不存在A', '不存在B')
        assert route == []

    def test_get_nearby_nodes(self):
        game_map = Map()
        nearby = game_map.get_nearby_nodes('沈阳', max_distance=2)
        assert len(nearby) > 0
        # 沈阳的邻居应该包含在附近节点中
        for neighbor, dist in nearby:
            assert dist <= 2

    def test_tick_day(self):
        game_map = Map()
        initial_positions = [u.current_node for u in game_map.faction_units]
        game_map.tick_day()
        # 动态棋子可能移动了
        for i, unit in enumerate(game_map.faction_units):
            if unit.alive:
                assert unit.current_node is not None

    def test_intelligence_tick(self):
        game_map = Map()
        game_map.intelligence.add_report('沈阳', 'pla', 0.9, '侦察')
        game_map.tick_day()
        report = game_map.intelligence.get_intel('沈阳')
        assert report['days_old'] == 1

    def test_control_states(self):
        assert CONTROL_STATES['pla'] == '解放军控制'
        assert CONTROL_STATES['soviet'] == '苏军控制'
        assert CONTROL_STATES['bandit'] == '土匪控制'
        assert CONTROL_STATES['rebel'] == '造反派控制'
        assert CONTROL_STATES['refugee'] == '流民聚集'
        assert CONTROL_STATES['battlefield'] == '交火区'
        assert CONTROL_STATES['empty'] == '无人区'

    def test_node_levels(self):
        game_map = Map()
        assert game_map.nodes['沈阳'].level == 1
        assert game_map.nodes['哈尔滨'].level == 1
        assert game_map.nodes['长春'].level == 1
        assert game_map.nodes['大连'].level == 2  # 大连在NODE_LEVELS中定义为2

    def test_connections_count(self):
        game_map = Map()
        # 检查每个节点至少3条出路(边界节点除外)
        boundary = {'漠河', '满洲里', '秦皇岛', '承德', '山海关'}
        for name, node in game_map.nodes.items():
            if name in boundary:
                continue
            assert len(node.connections) >= 1, f"{name} 连接不足"

    def test_map_repr(self):
        game_map = Map()
        repr_str = repr(game_map)
        assert 'Map' in repr_str
        assert 'nodes=' in repr_str

    def test_node_repr(self):
        node = MapNode('测试', 3, 0, 0)
        node.garrison = Garrison('pla', 100)
        r = repr(node)
        assert '测试' in r
        assert 'L3' in r

    def test_garrison_repr(self):
        g = Garrison('soviet', 350)
        r = repr(g)
        assert 'soviet' in r
        assert '350' in r

    def test_faction_unit_repr(self):
        unit = FactionUnit('苏军侦察连', 'soviet', 80, 50, '绥芬河')
        r = repr(unit)
        assert '苏军侦察连' in r
        assert 'soviet' in r

    def test_intelligence_repr(self):
        intel = Intelligence()
        r = repr(intel)
        assert 'Intelligence' in r

    def test_key_cities_connected(self):
        game_map = Map()
        key_cities = ['大连', '沈阳', '长春', '哈尔滨', '牡丹江', '丹东']
        for city in key_cities:
            assert city in game_map.nodes, f"{city} 未在地图中"
            assert len(game_map.nodes[city].connections) > 0, f"{city} 没有连接"

← 返回文件树 · 在 GitHub 上查看